前端html请求:
let url = '/indexController/getFileOutputStream?path='+param;
$("#filedownload").attr("href",url);
document.getElementById("filedownload").click();
java后端代码:
@RequestMapping("/getFileOutputStream")
public void getFileOutputStream(HttpServletResponse response,String path) {
response.setCharacterEncoding("UTF-8");
OutputStream out = null;
System.out.println(path);
System.out.println("==========getFileOutputStream=========文件路径:"+path);
File file = new File(path); //1、建立连接
BufferedInputStream is = null;
byte[] b = new byte[4096];
int len = 1024;
// 清空response
response.reset();
response.setContentType("application/x-download");//设置response内容的类型 普通下载类型
try {
response.setHeader("Content-disposition","attachment;filename="+ URLEncoder.encode(file.getName(), "UTF-8"));//设置头部信息
out = response.getOutputStream();
is = new BufferedInputStream(new FileInputStream(file));
while((len= is.read(b)) != -1) {
out.write(b,0,len);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
out.flush();
if(is!=null)
is.close();
if(out!=null)
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}