注意请求时加入:responseType: 'blob'url:写全了,因为前后端端口号不同

downloadImage(imgUrl) {

let formData = new FormData();

formData.append('fileName', this.getFilename(imgUrl)); // 用于后端下载文件的路径

axios

.post('http://localhost:8080/competition/award/downloadFile', formData, {

responseType: 'blob'

})

.then(response => {

if (response.status == 200) {

console.log(response)

let url = window.URL.createObjectURL(new Blob([response.data])) // 将获取的文件转化为blob格式

let a = document.createElement('a'); // 此处向下是打开一个储存位置

a.style.display = 'none';

a.href = url;

// 下面两行是自己项目需要的处理,总之就是得到下载的文件名(加后缀)即可

var fileName = this.getFilename(imgUrl);

a.setAttribute('download', fileName+ '.jpg');

document.body.appendChild(a);

a.click();//点击下载

document.body.removeChild(a);// 下载完成移除元素

window.URL.revokeObjectURL(url);// 释放掉blob对象

this.$message.success("文件下载成功") //删除弹窗

} else {

this.$message.error("文件下载失败")

}

})

},

getFilename(url) {

// 从图片链接中提取文件名

return url.substring(url.lastIndexOf('/')+1);

},

注:此代码借鉴了其他博客 后端用的MinIO:

@RequestMapping("/downloadFile")

public ResponseEntity download(String fileName) throws Exception {

return minioUtils.download(fileName, FileConfig.awardImg);

}

文章链接

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: