思路:
- 设置返回的内容格式为二进制
- 设置下载后的文件名称
- 读取文件流并写出Response的输出流
- 关闭文件输入流
/**
* 下载文件
*
* @param filepath 下载文件的路径
* @param filename 下载后文件的名称
*/
public static void download(HttpServletResponse response, String filepath, String filename) {
InputStream inputStream = null;
try {
// 设置返回类型为二进制
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-stream");
// 设置下载后的文件名称
response.setHeader("Content-Disposition",
"attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
// 写出二进制数据
OutputStream outputStream = response.getOutputStream();
inputStream = new FileInputStream(new File(filepath));
int len;
byte[] data = new byte[1024];
while ((len = inputStream.read(data)) != -1) {
outputStream.write(data, 0, len);
}
outputStream.flush();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
IoUtil.close(inputStream);
}
}