后台实现
/**
* 下载
*
* @param response
* @throws IOException
*/
@SysLog("4")
@GetMapping("/download")
@RequiresPermissions("basic:dc:download")
public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {
response.setContentType("application/octet-stream");
//文件路径
String path = request.getParameter("filePath");
SmbFile smbFile = new SmbFile(path);
if (!smbFile.exists()) {
return;
}
// fileName = URLEncoder.encode(fileName, "UTF-8");
// fileName = fileName.replaceAll("\\+", "%20");
// response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
outPut(smbFile, response);
}
/**
* 将文件以流的形式输出
*
* @param smbFile
* @param response
* @throws IOException
*/
public void outPut(SmbFile smbFile, HttpServletResponse response) throws IOException {
InputStream inputStream = smbFile.getInputStream();
OutputStream out = response.getOutputStream();
// byte[] b = new byte[1024 * 4];
// while ((inputStream.read(b)) != -1) {
// out.write(b);
// }
byte[] buffer = new byte[1024 << 3];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.flush();
inputStream.close();
out.close();
}
VUE 实现
downloadFile () {
this.$nextTick(() => {
if (this.fileList.length) {
let filePath = this.fileList[0].path.toString()
let fileName = filePath.substring(filePath.lastIndexOf('/') + 1, filePath.length)
this.loading = true
this.$http({
url: this.$http.adornUrl('/download'),
method: 'get',
params: this.$http.adornParams({
'filePath': filePath
}),
responseType: 'blob'
}).then(({data}) => {
this.loading = false
const link = document.createElement('a')
let blob = new Blob([data], {type: 'application/octet-stream'});
if (blob.size === 0) {
this.$message.error('文件不存在')
return
}
// let fileName = new Date().getTime()
// for IE
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob, fileName);
} else {
// for Non-IE (chrome, firefox etc.)
link.style.display = 'none'
link.href = URL.createObjectURL(blob);
link.setAttribute('download', fileName)
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
}
})
// let token = this.$cookie.get('token')
// window.location.href = encodeURI(this.$http.adornUrl(`/basic/dc/download?token=${token}&filePath=${filePath}`))
}
})
}