如何利用后端给的url,前端下载图片、音频、视频等文件
后端給了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 進行匹配!
?
總結
以上是生活随笔為你收集整理的如何利用后端给的url,前端下载图片、音频、视频等文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 暴雪即将公布《暗黑破坏神3》新职业
- 下一篇: java网络编程--IP与InetAdd