纯前端处理

一、a标签下载

浏览器下载的方法有很多,最简单可以通过html的a标签下载

  1. <a href="./我爱你.mp4" download="下载名称">点击下载</a>

因此我们可以通过使用dom操作生成a标签,实现js下载

  1. function downloadToLocal(url,fileName){
  2. let link = document.createElement('a') //创建a标签
  3. link.style.display = 'none' //将a标签隐藏
  4. link.href = url //给a标签添加下载链接
  5. link.setAttribute('download', fileName) // 此处注意,要给a标签添加一个download属性,属性值就是文件名称 否则下载出来的文件是没有属性的,空白白
  6. document.body.appendChild(link)
  7. link.click() //执行a标签
  8. }
  9. export { downloadToLocal }

但是a标签下载存在同源策略,如果下载的文件是非同源的,虽然加了download属性,有些格式还是会直接打开预览(如mp4、jpg),而不是调用浏览器的下载事件。

二、blob下载

为解决此问题,可以通过二进制流进行下载,即通过blob转为二进制流下载,Blob对象可以看做是存放二进制数据的容器。

  1. const downloadRes = async () => {
  2. // 内容转变成blob地址
  3. let response = await fetch("https://vca-resource.obs.cn-north-4.myhuaweicloud.com/%E6%88%91%E7%88%B1%E4%BD%A01.mp4",{
  4. method: 'GET',
  5. mode: 'cors',
  6. });
  7. let blob = await response.blob();
  8. // 创建隐藏的可下载链接
  9. let objectUrl = window.URL.createObjectURL(blob);
  10. let a = document.createElement('a');
  11. a.href = objectUrl;
  12. a.download = "测试123";
  13. a.click()
  14. a.remove();
  15. }

此方法的缺点是如果文件大,则速度较慢。因为需要拿到地址返回的二进制流(大小和需要下载的大小相同),才能让用户进行下载。但此方法兼容性较好,适合小文件。

三、download.js

download.js是一个前端下载库
下载调用的方法download(data, strFileName, strMimeType)

  • data为二进制流 必选,如果只传递一个参数,data可以是url,download.js会通过blob方法转为流
  • strFileName是文件名 可选
  • strMimeType是文件类型 可选

download.js源码,放入utils后,直接import使用即刻。

  1. (function (root, factory) {
  2. if (typeof define === 'function' && define.amd) {
  3. // AMD. Register as an anonymous module.
  4. define([], factory);
  5. } else if (typeof exports === 'object') {
  6. // Node. Does not work with strict CommonJS, but
  7. // only CommonJS-like environments that support module.exports,
  8. // like Node.
  9. module.exports = factory();
  10. } else {
  11. // Browser globals (root is window)
  12. root.download = factory();
  13. }
  14. }(this, function () {
  15. return function download(data, strFileName, strMimeType) {
  16. var self = window, // this script is only for browsers anyway...
  17. defaultMime = "application/octet-stream", // this default mime also triggers iframe downloads
  18. mimeType = strMimeType || defaultMime,
  19. payload = data,
  20. url = !strFileName && !strMimeType && payload,
  21. anchor = document.createElement("a"),
  22. toString = function(a){return String(a);},
  23. myBlob = (self.Blob || self.MozBlob || self.WebKitBlob || toString),
  24. fileName = strFileName || "download",
  25. blob,
  26. reader;
  27. myBlob= myBlob.call ? myBlob.bind(self) : Blob ;
  28. if(String(this)==="true"){ //reverse arguments, allowing download.bind(true, "text/xml", "export.xml") to act as a callback
  29. payload=[payload, mimeType];
  30. mimeType=payload[0];
  31. payload=payload[1];
  32. }
  33. if(url && url.length< 2048){ // if no filename and no mime, assume a url was passed as the only argument
  34. fileName = url.split("/").pop().split("?")[0];
  35. anchor.href = url; // assign href prop to temp anchor
  36. if(anchor.href.indexOf(url) !== -1){ // if the browser determines that it's a potentially valid url path:
  37. var ajax=new XMLHttpRequest();
  38. ajax.open( "GET", url, true);
  39. ajax.responseType = 'blob';
  40. ajax.onload= function(e){
  41. download(e.target.response, fileName, defaultMime);
  42. };
  43. setTimeout(function(){ ajax.send();}, 0); // allows setting custom ajax headers using the return:
  44. return ajax;
  45. } // end if valid url?
  46. } // end if url?
  47. //go ahead and download dataURLs right away
  48. if(/^data\:[\w+\-]+\/[\w+\-]+[,;]/.test(payload)){
  49. if(payload.length > (1024*1024*1.999) && myBlob !== toString ){
  50. payload=dataUrlToBlob(payload);
  51. mimeType=payload.type || defaultMime;
  52. }else{
  53. return navigator.msSaveBlob ? // IE10 can't do a[download], only Blobs:
  54. navigator.msSaveBlob(dataUrlToBlob(payload), fileName) :
  55. saver(payload) ; // everyone else can save dataURLs un-processed
  56. }
  57. }//end if dataURL passed?
  58. blob = payload instanceof myBlob ?
  59. payload :
  60. new myBlob([payload], {type: mimeType}) ;
  61. function dataUrlToBlob(strUrl) {
  62. var parts= strUrl.split(/[:;,]/),
  63. type= parts[1],
  64. decoder= parts[2] == "base64" ? atob : decodeURIComponent,
  65. binData= decoder( parts.pop() ),
  66. mx= binData.length,
  67. i= 0,
  68. uiArr= new Uint8Array(mx);
  69. for(i;i<mx;++i) uiArr[i]= binData.charCodeAt(i);
  70. return new myBlob([uiArr], {type: type});
  71. }
  72. function saver(url, winMode){
  73. if ('download' in anchor) { //html5 A[download]
  74. anchor.href = url;
  75. anchor.setAttribute("download", fileName);
  76. anchor.className = "download-js-link";
  77. anchor.innerHTML = "downloading...";
  78. anchor.style.display = "none";
  79. document.body.appendChild(anchor);
  80. setTimeout(function() {
  81. anchor.click();
  82. document.body.removeChild(anchor);
  83. if(winMode===true){setTimeout(function(){ self.URL.revokeObjectURL(anchor.href);}, 250 );}
  84. }, 66);
  85. return true;
  86. }
  87. // handle non-a[download] safari as best we can:
  88. if(/(Version)\/(\d+)\.(\d+)(?:\.(\d+))?.*Safari\//.test(navigator.userAgent)) {
  89. url=url.replace(/^data:([\w\/\-\+]+)/, defaultMime);
  90. if(!window.open(url)){ // popup blocked, offer direct download:
  91. if(confirm("Displaying New Document\n\nUse Save As... to download, then click back to return to this page.")){ location.href=url; }
  92. }
  93. return true;
  94. }
  95. //do iframe dataURL download (old ch+FF):
  96. var f = document.createElement("iframe");
  97. document.body.appendChild(f);
  98. if(!winMode){ // force a mime that will download:
  99. url="data:"+url.replace(/^data:([\w\/\-\+]+)/, defaultMime);
  100. }
  101. f.src=url;
  102. setTimeout(function(){ document.body.removeChild(f); }, 333);
  103. }//end saver
  104. if (navigator.msSaveBlob) { // IE10+ : (has Blob, but not a[download] or URL)
  105. return navigator.msSaveBlob(blob, fileName);
  106. }
  107. if(self.URL){ // simple fast and modern way using Blob and URL:
  108. saver(self.URL.createObjectURL(blob), true);
  109. }else{
  110. // handle non-Blob()+non-URL browsers:
  111. if(typeof blob === "string" || blob.constructor===toString ){
  112. try{
  113. return saver( "data:" + mimeType + ";base64," + self.btoa(blob) );
  114. }catch(y){
  115. return saver( "data:" + mimeType + "," + encodeURIComponent(blob) );
  116. }
  117. }
  118. // Blob but not URL support:
  119. reader=new FileReader();
  120. reader.onload=function(e){
  121. saver(this.result);
  122. };
  123. reader.readAsDataURL(blob);
  124. }
  125. return true;
  126. }; /* end download() */
  127. }));

四、 华为obs二进制下载

  1. var obsClient = new ObsClient({
  2. access_key_id: 'xxx',
  3. secret_access_key: 'xxx',
  4. server: 'xxx'
  5. });
  6. obsClient.getObject({
  7. Bucket : 'vca-resource',
  8. Key : 'upload/我爱你1.mp4',
  9. SaveByType : 'arraybuffer'
  10. }, function (err, result) {
  11. if(err){
  12. console.error('Error-->' + err);
  13. }else{
  14. console.log('Status-->' + result.CommonMsg.Status);
  15. if(result.CommonMsg.Status < 300 && result.InterfaceResult){
  16. // 读取对象字节长度
  17. console.log('Object Length:\n');
  18. console.log(result.InterfaceResult.Content.byteLength);
  19. console.log(result);
  20. this.$downloadToLocal(result.InterfaceResult.Content, "测试123.mp4"); //a标签下载
  21. // downloadVideo(result.InterfaceResult.Content,"测试.mp4")
  22. }
  23. }
  24. });

后端处理

一、后端返回二进制流

  1. const fs = require('fs');
  2. ctx.type = "video/mpeg4";
  3. ctx.body = fs.readFileSync(urls.video);

前端配合

  1. this.$axios({
  2. method: 'get', //请求方法 get post
  3. url: url, //请求地址
  4. // params:params,
  5. // headers:{
  6. // 'Authorization':`Bearer ${getToken()}`
  7. // },
  8. responseType: 'blob' //关键配置项
  9. }).then(res=>{
  10. this.loading = false;
  11. console.log(res);
  12. downloadVideo(res.data,this.resultData.media_name + '.mp4');
  13. })

二、华为云处理

ContentDisposition 设置为 attachment

在前端请求修改 该视频的ContentDisposition

  1. videoUrl = videoUrl.replace("http://resources.bjvca.com","https://vca-resource.obs.cn-north-4.myhuaweicloud.com");
  2. this.$axios({
  3. method:"put",
  4. url:videoUrl + "?metadata=",
  5. headers:{
  6. "Content-Disposition":"attachment",
  7. "x-obs-metadata-directive":"REPLACE_NEW"
  8. }
  9. }).then(res=>{
  10. this.$downloadToLocal(videoUrl,this.resultData.media_name + '.mp4')
  11. })