本文最后更新于 1220 天前,其中的信息可能已经有所发展或是发生改变。
JAVA接口
当然也可以返回void方法。
@RequestMapping("/download")
public String fileDownLoad(HttpServletResponse response, @RequestParam("fileName") String fileName){
File file = new File(downloadFilePath +'/'+ fileName);
if(!file.exists()){
return "下载文件不存在";
}
response.reset();
response.setContentType("application/octet-stream");
response.setCharacterEncoding("utf-8");
response.setContentLength((int) file.length());
response.setHeader("Content-Disposition", "attachment;filename=" + fileName );
try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));) {
byte[] buff = new byte[1024];
OutputStream os = response.getOutputStream();
int i = 0;
while ((i = bis.read(buff)) != -1) {
os.write(buff, 0, i);
os.flush();
}
} catch (IOException e) {
e.printStackTrace();
return "下载失败";
}
return "下载成功";
}
vue的下载处理
Axios接口添加返回类型:
getDownload:function({filename}){
var param={
fileName : fileName
};
return Axios.post('/api/common/getDownload', param, {response:'blob'});
}
vue前端调用a标签下载:
apis.common.getDownload(param).then((data)=>{
if(data){
let dataBlob = new Blob([data.data]);
if(dataBlob.size > 0){
let link = document.createElement("a");
link.style.display = 'none';
link.href = window.URL.createObjectURL(dataBlob);
link.setAttribute("download", rowData.fileName);
document.body.appendChild(link);
link.click();
URL.revokeObjectURL(link.href);
document.body.removeChild(link);
this.$message({message: '下载成功', type: 'success'});
}else{
this.$message({message: '下载失败,文件不存在', type: 'error'});
}
}else{
this.$message({message: '下载异常,请重试', type: 'error'});
}
})