解决方法:
前端在请求下载文件接口时,要设置responseType为blob。
前端代码:
export function download(url, params) {
return request({
url: url + '?' + qs.stringify(params, { indices: false }),
method: 'get',
responseType: 'blob'
})
}
后端下载文件接口:
- 控制器:
@ApiOperation(value = "下载模板" , notes = " \n author:LiFang ")
@GetMapping("/downloadTemplate")
public Result<Void> downloadTemplate(HttpServletRequest request, HttpServletResponse response) throws FileNotFoundException {
File file = ResourceUtils.getFile("classpath:template/excel/学生信息模板.xlsx");
FileUtils.downloadFile(request, response, file, false);
return Result.success();
}
- 下载文件工具类
FileUtils.java
public class FileUtils extends cn.hutool.core.io.FileUtil {
public static void downloadFile(HttpServletRequest request, HttpServletResponse response, File file,
boolean deleteOnExit) {
response.setCharacterEncoding(request.getCharacterEncoding());
response.setContentType("application/octet-stream");
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
IOUtils.copy(fis, response.getOutputStream());
response.flushBuffer();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
if (deleteOnExit) {
file.deleteOnExit();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
https://www.cnblogs.com/zhusf/p/11123464.html
https://tool.oschina.net/commons/
https://www.cnblogs.com/lyz1991/p/11468895.html