一、使用背景
一般来说,当我们上传文件之后,便会要提供文件下载的入口。而其实文件下载就是获取文件,并将文件内容写入到HTTP返回响应的过程。
二、前端实现方式
- 构造form表单提交
1、引入相关js
<script src="${basepath}/jquery-3.3.1/jquery-3.3.1.js" type="text/javascript"></script>
<script src="${basepath}/downLoadFile.js" type="text/javascript" ></script>
2、在下载按钮上绑定点击事件
<button onclick=downLoadFile('"+fileId+"') class='btn btn-info btn-sm pull-right'>下 载</button>
3、downLoadFile.js源码
function downLoadFile(id){
var form=$("<form>"); // 定义一个form表单
form.attr("style","display:none");
form.attr("target","_blank");
form.attr("method","post");
form.attr("action","/download"); // 此处填写文件下载提交路径
var input1=$("<input>");
input1.attr("type","hidden");
input1.attr("name","id"); // 后台接收参数名
input1.attr("value",id);
$("body").append(form); // 将表单放置在web中
form.append(input1);
form.submit(); // 表单提交
}
三、后台Java实现部分代码
/**
* 附件下载
*/
@RequestMapping(value = "download")
public String downloadFile( HttpServletRequest request, Model model,HttpServletResponse response, RedirectAttributes redirectAttributes,String id) {
shareFile = fileService.get(id);
if(shareFile != null){
String fileName = shareFile.getFilename().replace(" ", "");
response.reset();
response.setContentType("application/octet-stream; charset=utf-8");
String agent = request.getHeader("USER-AGENT"); // 获取浏览器类型
String downLoadName = null;
try {
// Edge
if (null != agent && -1 != agent.indexOf("Edge")) {
downLoadName = java.net.URLEncoder.encode(fileName, "UTF-8");
// Firefox
} else if (null != agent && -1 != agent.indexOf("Firefox")) {
downLoadName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
// Chrome或360
} else if (null != agent && -1 != agent.indexOf("Chrome")) {
downLoadName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
} else {
downLoadName = java.net.URLEncoder.encode(fileName, "UTF-8");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
response.setHeader("Content-Disposition", "attachment; filename="+downLoadName);
InputStream in = fileService.downloadFile(shareFile); // 此处是获取文件输入流
OutputStream out;
try {
out = response.getOutputStream();
//写文件
int b;
while((b = in.read()) != -1) {
out.write(b);
}
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}