前端
这里的el-button 是在el-table中的table列中
<Button type="text" size="small" @click="downloadFile(scope.$index,scope.row)">下载</Button>
downloadFile (index, row) {
downLoad({fileName:row.fileAllName,filePath:row.filePath}).then(res => {
this.download(res, row)
}).catch(err => {
this.$message.error('下载失败:' + err)
})
},
download (data, row) {
if (!data) {
return
}
let url = window.URL.createObjectURL(new Blob([data]))
let link = document.createElement('a')
link.style.display = 'none'
link.href = url
// 获取文件名
// download 属性定义了下载链接的地址而不是跳转路径
link.setAttribute('download', row.fileName)
document.body.appendChild(link)
link.click()
},
前端请求API
export function downLoad (data) {
return request({
url: '/file/download',
method: 'post',
responseType: 'blob',
data
})
}
后台请求
@PostMapping("/download")
public void doenloadFile(@RequestBody Map<String,Object> map ,HttpServletResponse response) throws Exception {
String fileName= (String) map.get("fileName");
String filePath= (String) map.get("filePath");
File file = new File(filePath+"/"+fileName);
if(file.exists()) {
FileInputStream input=null;
byte[] data = null;
try {
input = new FileInputStream(file);
data = new byte[input.available()];
input.read(data);
response.setContentType("application/x-download;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment;filename*=UTF-8"+URLEncoder.encode(fileName,"UTF-8"));
response.getOutputStream().write(data);
} catch (Exception e) {
logger.error("下载失败,原因如下:", e);
}finally {
input.close();
}
}else {
// 未找到文件
}
}