@RequestMapping(value = "/download/test.apk")
public void downloadEnterpriseApk(HttpServletResponse response) {
//1.获取要下载的文件的绝对路径,注意windows和Linux中的斜杠不同的问题
String realPath = "/download/test.apk";
// String realPath = "D:\\release\\test.apk";
//2.获取要下载的文件名,这个只能用在windows中使用,
//所以直接写成固定更方便,小伙伴根据自己的需求改动
// String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
String fileName = "test.apk";
System.out.println("response" +response+ ",fileName:" + fileName);
//3.设置content-disposition响应头控制浏览器以下载的形式打开文件
response.setHeader("content-disposition", "attachment;filename=" + fileName);
OutputStreamWriter writer = null;
try {
/*因为要写入错误的信息,所以优先初始化OutputStreamWriter*/
writer = new OutputStreamWriter(response.getOutputStream(), "UTF-8");
File file = new File(realPath);
//4.获取要下载的文件输入流
InputStream in = new FileInputStream(file);
System.out.print("文件大小:"+file.length());
//如果不填setContentLength,不会报错,但是下载的时候会显示大小未知
response.setContentLength((int) file.length());
int len;
//5.创建数据缓冲区
byte[] buffer = new byte[1024];
//6.通过response对象获取OutputStream流
OutputStream out = response.getOutputStream();
//7.将FileInputStream流写入到buffer缓冲区
while ((len = in.read(buffer)) > 0) {
//8.使用OutputStream将缓冲区的数据输出到客户端浏览器
out.write(buffer, 0, len);
}
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
String data = "报错了:" + e.getMessage();
try{
if (writer != null){
/*这个是为了下载错误的时候,给客户端返回错误信息,方便定位,
否则只能后台自己排查,比较麻烦了*/
writer.write(data);
writer.close();
}
}catch (IOException e2) {
e2.printStackTrace();
}
}
}
参考资料
https://www.cnblogs.com/Donnnnnn/p/7902718.html
https://www.cnblogs.com/xdp-gacl/p/3789624.html