java下载文件工具类
1.封装工具类
public class FileDownloadUtil {
public static void fileDownload(String path, HttpServletResponse response) throws IOException {
File file = new File(path);
log.info(file.getPath());
String filename = file.getName();
String ext = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
log.info("文件后缀名:" + ext);
FileInputStream fileInputStream = new FileInputStream(file);
InputStream fis = new BufferedInputStream(fileInputStream);
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
response.setCharacterEncoding("UTF-8");
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
response.addHeader("Content-Length", "" + file.length());
OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
outputStream.write(buffer);
outputStream.flush();
}
}
2.调用接口
@CrossOrigin
@RequestMapping("/download")
public void download(HttpServletResponse response) throws FileDownloadException {
String path = this.getClass().getClassLoader().getResource("clothing-import.xlsx").getPath();
try {
FileDownloadUtil.fileDownload(path, response);
} catch (IOException e) {
log.error("模板下载失败!");
throw new FileDownloadException(ErrorCode.EXCEL_DOWNLOAD_ERROR.getCode(), ErrorCode.EXCEL_DOWNLOAD_ERROR.getMsg());
}
}
3.前端调用
methods: {
filedownload (data) {
if (!data) {
return
}
let url = window.URL.createObjectURL(new Blob([data]))
let link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', '衣物导入模板.xlsx')
document.body.appendChild(link)
link.click()
},
download(){
getDownload().then((res) => {
this.filedownload(res)
});
},
}
3.1 封装的request
export function getDownload() {
return request({
url: '/clothes/download',
method: 'get',
responseType: 'blob',
})
}