从Springboot项目中下载文件的具体过程
时间:2022-01-20 09:17:41|栏目:JAVA代码|点击: 次
最近在做一个临时的项目,APP端在检测到程序有更新时,需要去后台下载新的安装包。具体过程如下:
controller层:
/**
* 下载app
* @param response
*/
@RequestMapping("downApp")
@ResponseBody
public void Download(HttpServletResponse response) {
String fileName ="wuye.apk";
String result = FileUtil.downloadFile(response, fileName);
log.info("app包下载结果:",result);
}
工具类:
public class FileUtil {
public static String downloadFile(HttpServletResponse response, String fileName) {
File path =null;
response.setHeader("content-type","application/octet-stream");
response.setContentType("application/octet-stream");
try {
response.setHeader("Content-Disposition","attachment;filename=" + java.net.URLEncoder.encode(fileName,"UTF-8"));
}catch (UnsupportedEncodingException e2) {
e2.printStackTrace();
}
byte[] buff =new byte[1024];
BufferedInputStream bis =null;
OutputStream os =null;
try {
path =new File(ResourceUtils.getURL("classpath:").getPath());
os = response.getOutputStream();
bis =new BufferedInputStream(new FileInputStream(new File(path +"/doc/" + fileName)));
int i = bis.read(buff);
while (i != -1) {
os.write(buff,0, buff.length);
os.flush();
i = bis.read(buff);
}
}catch (FileNotFoundException e1) {
//e1.getMessage()+"系统找不到指定的文件";
return "系统找不到指定的文件";
}catch (IOException e) {
e.printStackTrace();
}finally {
if (bis !=null) {
try {
bis.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}
return "success";
}
访问:http://127.0.0.1:8081/ymd/downApp 文件就下载下来了,本方法借鉴了 网络上的一些文章
上一篇:springboot清除字符串前后空格与防xss攻击方法
栏 目:JAVA代码
下一篇:Java实现银行ATM系统
本文地址:http://www.codeinn.net/misctech/190809.html


阅读排行
- 1Java Swing组件BoxLayout布局用法示例
- 2java中-jar 与nohup的对比
- 3Java邮件发送程序(可以同时发给多个地址、可以带附件)
- 4Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type异常
- 5Java中自定义异常详解及实例代码
- 6深入理解Java中的克隆
- 7java读取excel文件的两种方法
- 8解析SpringSecurity+JWT认证流程实现
- 9spring boot里增加表单验证hibernate-validator并在freemarker模板里显示错误信息(推荐)
- 10深入解析java虚拟机




