后端给了url,让前端处理下载,刚开始只处理图片url下载,然后用最简单的方式,创建a标签,叫download属性,发现竟然不行,找了一下原因,原来是url地址跨域了,这里需要让后端处理一下服务器对url跨域问题,然后前端代码线上:
downPic(urls, fileName) {
const image = new Image()
// 解决跨域 Canvas 污染问题
image.setAttribute('crossOrigin', 'anonymous')
image.onload = () => {
const canvas = document.createElement('canvas')
canvas.width = image.width
canvas.height = image.height
const context = canvas.getContext('2d')
context.drawImage(image, 0, 0, image.width, image.height)
canvas.toBlob((blob) => {
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.download = fileName || 'photo'
a.href = url
a.click()
a.remove()
URL.revokeObjectURL(url)
})
}
image.src = urls
},
后端处理服务器跨域问题之后,这种方式的确可以下载图片;但是!后来增加需求,要同时满足下载音频和视频,用这种方式就不行了!只能想其他办法:
后来去网上找了很多办法,最终了解到,想要下载音频和视频 只能让后端把url转成文件流格式的数据,然后前端才能下载;上代码:
downPic(urls, fileName) {
let type = urls.split(".");
type = type[type.length - 1];
httpParmas(w_url.download, { fileUrl: urls }).then(res => {
if (res) {
let blobUrl = window.URL.createObjectURL(new Blob([res], { type: downType[type] }))
let link = document.createElement('a')
document.body.appendChild(link)
link.style.display = 'none'
link.href = blobUrl
// 设置a标签的下载属性,设置文件名及格式,后缀名最好让后端在数据格式中返回
link.setAttribute('download', fileName)
// 自触发click事件
link.click()
document.body.removeChild(link)
window.URL.revokeObjectURL(blobUrl);
}
})
},
标红的地方是重点,我这边要下载不同格式的文件,格式是前端这边来定的,后端不会告诉前端,然后我这边就只能通过传给后端接口的url的后缀名来匹配是什么格式的文件。
这时候遇到一个坑,接口通了 但是下载不了,上图
这里一定要在接口的地方加上responseType:'blob'这个属性,然后文件就可以下载下来了;
最后说一下 type 格式 可以去百度一下 然后自己写个js 进行匹配!