1、下载代码
1、controller层代码
//这里只gei
@GetMapping(value = "/expert/template/download")
public void downloadExpertTemplate(HttpServletResponse response){
//filePath 是文件路径 ,可以根据需求自行赋值
String filePath = FileEnum.ROOT_FILE_PATH.getContent() + FileEnum.IMPORT_TEMPLATE_PATH.getContent() + "咨询专家信息导入模板.xlsx";
try {
FileUtil.downloadFile(response,filePath,false);
}catch (Exception e){
e.printStackTrace();
}
}
2、FileUtil类
public class FileUtil{
/**
* 文件下载
*
* @param response 响应流
* @param filePath 文件路径 绝对路径
* @param isDelete 下载后是否删除源文件
* @author
* @Date: Created in 2018/6/26
*/
public void downloadFile(HttpServletResponse response, String filePath, boolean isDelete) throws IOException {
File file = new File(filePath);
if (file.exists()) {
// 设置强制下载不打开
response.setContentType("application/force-download;charset=UTF-8");
// 设置文件名
System.out.println(file.getName());
response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(file.getName(),"utf-8"));
byte[] buffer = new byte[1024];
FileInputStream fis;
BufferedInputStream bis;
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
bis.close();
fis.close();
os.close();
//下载后是否删除源文件(压缩包下载后可以删除)
if (isDelete) {
file.delete();
}
}else {
throw new IllegalArgumentException("file not exist");
}
}
}
3、遇到的问题
问题: 在地址栏输入请求路径之后,下载下来的文件是这个样子的,只有一个download的文件名,没有文件类型的后缀名
原因: 问题出在下面
导致问题的代码是这样的,
response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(file.getName()));
正确的代码应该是这样的,注意encode()的参数
response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(file.getName(),"utf-8"));