springboot直接从浏览器下载文件
Posted Firm陈
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot直接从浏览器下载文件相关的知识,希望对你有一定的参考价值。
@GetMapping("file/download")
public void downloadDevtool(HttpServletRequest request, HttpServletResponse response) throws IOException {
String property = System.getProperty("user.dir");
String path = property + "/src/main/resources/file/text.txt";
File file = new File(path);
String filename = path.substring(path.lastIndexOf("/")+1);
response.setContentType("application/x-download");
response.setHeader("content-Disposition", "attachment;filename=" + filename);
InputStream in = null;
try {
in = new FileInputStream(file);
int len = 0;
byte buffer[] = new byte[1024];
OutputStream out = response.getOutputStream();
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
以上是关于springboot直接从浏览器下载文件的主要内容,如果未能解决你的问题,请参考以下文章
ie浏览器网页中直接打开文件,没有下载到本地,并在修改后保存,文件还在吗?从哪里找?XP系统
Java Springboot 根据图片链接生成图片下载链接 及 多个图片打包zip下载链接