1.前台
发送下载请求
1.form表单提交请求
1.html
尽量不要放中文,可能会乱码
<%-- 用于下载提交请求--%>
<form id="downloadForm" action="${BASEPATH}annexManage/download" method="post"
type="hidden">
<input id="filePath" name="filePath" value="" type="hidden"/>
<input id="fileName" name="fileName" value="" type="hidden"/>
<input id="extName" name="extName" value="" type="hidden"/>
</form>
2.js
$("#downloadForm").submit();
注意:
不要用ajax请求提交下载,response就算改成了
"application/x-msdownload; charset=UTF-8")
也不行, 因为ajax是 返回结果的response返回到了你的js代码里, 所以,根本下载不了文件
2.response
response是对于与request的返回
一般后台会向前台返回json字符串,当然也可以返回文件文件流,
3.远程文件下载类
文件路径是URL
https://www.baidu.com/img/bd_logo1.png
public static void downloadRemoteFile(String fileSrc, HttpServletResponse response) throws IOException {
fileSrc = fileSrc.replace("\\", "/");
String fileName = FileNameUtils.getName(fileSrc);
//进行转码, 防止中文名出错
fileSrc = FileNameUtils.getPath(fileSrc) + URLEncoder.encode(fileName, "utf-8");
//如果文件名有空格,空格会变成“+”, 故在此将 “+” 还原成空格。
fileSrc=fileSrc.replaceAll("\\+", "%20");
URL url = new URL(fileSrc);
BufferedInputStream in = new BufferedInputStream(url.openStream());
response.reset();
response.setContentType("application/x-msdownload; charset=UTF-8");
response.setHeader("Content-Disposition",
"attachment;filename=\"" + URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20") + "\"");
OutputStream out = response.getOutputStream();
IOUtils.copy(in, out);
in.close();
out.close();
}
4.本地文件下载
文件路径是本地路径
String fileSrc="C:\\Users\\\\Desktop\\中文.xlsx";
public static void downloadLocalFile(HttpServletResponse response , String path) throws IOException, URISyntaxException {
Path file= Paths.get(path);
if(Files.exists(file)){
response.setContentType("APPLICATION/OCTET-STREAM");
response.addHeader("Content-Disposition", "attachment; filename="+ URLEncoder.encode(FileNameUtils.getName(fileSrc), "UTF-8") );
try
{
Files.copy(file, response.getOutputStream());
response.getOutputStream().flush();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
}