前端Vue代码:
downloadDocument (row) {
let vm = this
this.$ajax.post('/api/downloadDocument', row, {responseType: 'blob'})
.then(function (res) {
if (!res.data) {
return
}
let url = window.URL.createObjectURL(new Blob([res.data]))
let link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', row.fileName)
document.body.appendChild(link)
link.click()
}
).catch(function (error) {
let reader = new FileReader()
reader.onload = function () {
let jsonData = JSON.parse(this.result)
vm.$message(jsonData.message)
}
reader.readAsText(error.response.data)
})
},
后端代码:
controller:
@RequestMapping(value = "/downloadDocument", method = RequestMethod.POST)
public void downloadDocument(@RequestBody DocumentDto documentDto, HttpServletResponse response)
throws IOException {
documentService.downloadDocument(documentDto, response.getOutputStream());
response.flushBuffer();
}
service:
@Override
public void downloadDocument(DocumentDto documentDto, OutputStream os) throws IOException {
String fileName = documentDto.getFileName();
Path documentPath = Paths.get(this.fileStorageLocation, documentDto.getFileFolderName()).toAbsolutePath()
.normalize().resolve(fileName);
org.apache.commons.io.FileUtils.copyFile(documentPath.toFile(), os);
}
Good Luck,
Cheers!