各种文件下载
/** 文件下载工具类 */
public void downloadFile(HttpServletResponse response,String url)
throws UnsupportedEncodingException {
File file = new File(url);
// 配置文件下载
response.setCharacterEncoding("UTF-8");
response.setContentType("application/x-excel");
// 下载文件能正常显示中文
response.setHeader(
"Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
// 实现文件下载
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
response.setHeader("Content-Length", fis.available() + ""); // 内容长度
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
System.out.println("Download the song successfully!");
os.close();
} catch (Exception e) {
System.out.println("Download the song failed!");
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
测试:
本地测试
服务器线上测试