在开发中遇到需要下载文件的需求,现在把文件下载整理一下。
传统文件下载方式有超链接下载或者后台程序下载两种方式。通过超链接下载时,如果浏览器可以解析,那么就会直接打开,如果不能解析,就会弹出下载框;而后台程序下载就必须通过两个响应头和一个文件的输入流。
后台程序下载
两个响应头:
Content-Type:其值有比如 text/html;charset=utf-8
Content-Disposition:其值为 attachment;filename=文件名 以附件形式打开
流:需要获取文件的输入流,然后通过response对象的输出流输出到客户端。
1.Spring-ResponseEntity响应json格式接口,进行下载文件
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
@RequestMapping(value = "/demoDown") //匹配的是href中的download请求
public ResponseEntity download(HttpServletRequest request, @RequestParam("filename") String filename,Model model) throws IOException {
String downloadFilePath = request.getSession().getServletContext().getRealPath("uploadbill");
f