纯前端处理
一、a标签下载
浏览器下载的方法有很多,最简单可以通过html的a标签下载
<a href="./我爱你.mp4" download="下载名称">点击下载</a>
因此我们可以通过使用dom操作生成a标签,实现js下载
function downloadToLocal(url,fileName){
let link = document.createElement('a') //创建a标签
link.style.display = 'none' //将a标签隐藏
link.href = url //给a标签添加下载链接
link.setAttribute('download', fileName) // 此处注意,要给a标签添加一个download属性,属性值就是文件名称 否则下载出来的文件是没有属性的,空白白
document.body.appendChild(link)
link.click() //执行a标签
}
export { downloadToLocal }
但是a标签下载存在同源策略,如果下载的文件是非同源的,虽然加了download属性,有些格式还是会直接打开预览(如mp4、jpg),而不是调用浏览器的下载事件。
二、blob下载
为解决此问题,可以通过二进制流进行下载,即通过blob转为二进制流下载,Blob对象可以看做是存放二进制数据的容器。
const downloadRes = async () => {
// 内容转变成blob地址
let response = await fetch("https://vca-resource.obs.cn-north-4.myhuaweicloud.com/%E6%88%91%E7%88%B1%E4%BD%A01.mp4",{
method: 'GET',
mode: 'cors',
});
let blob = await response.blob();
// 创建隐藏的可下载链接
let objectUrl = window.URL.createObjectURL(blob);
let a = document.createElement('a');
a.href = objectUrl;
a.download = "测试123";
a.click()
a.remove();
}
此方法的缺点是如果文件大,则速度较慢。因为需要拿到地址返回的二进制流(大小和需要下载的大小相同),才能让用户进行下载。但此方法兼容性较好,适合小文件。
三、download.js
download.js是一个前端下载库
下载调用的方法download(data, strFileName, strMimeType)
- data为二进制流 必选,如果只传递一个参数,data可以是url,download.js会通过blob方法转为流
- strFileName是文件名 可选
- strMimeType是文件类型 可选
download.js源码,放入utils后,直接import使用即刻。
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define([], factory);
} else if (typeof exports === 'object') {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory();
} else {
// Browser globals (root is window)
root.download = factory();
}
}(this, function () {
return function download(data, strFileName, strMimeType) {
var self = window, // this script is only for browsers anyway...
defaultMime = "application/octet-stream", // this default mime also triggers iframe downloads
mimeType = strMimeType || defaultMime,
payload = data,
url = !strFileName && !strMimeType && payload,
anchor = document.createElement("a"),
toString = function(a){return String(a);},
myBlob = (self.Blob || self.MozBlob || self.WebKitBlob || toString),
fileName = strFileName || "download",
blob,
reader;
myBlob= myBlob.call ? myBlob.bind(self) : Blob ;
if(String(this)==="true"){ //reverse arguments, allowing download.bind(true, "text/xml", "export.xml") to act as a callback
payload=[payload, mimeType];
mimeType=payload[0];
payload=payload[1];
}
if(url && url.length< 2048){ // if no filename and no mime, assume a url was passed as the only argument
fileName = url.split("/").pop().split("?")[0];
anchor.href = url; // assign href prop to temp anchor
if(anchor.href.indexOf(url) !== -1){ // if the browser determines that it's a potentially valid url path:
var ajax=new XMLHttpRequest();
ajax.open( "GET", url, true);
ajax.responseType = 'blob';
ajax.onload= function(e){
download(e.target.response, fileName, defaultMime);
};
setTimeout(function(){ ajax.send();}, 0); // allows setting custom ajax headers using the return:
return ajax;
} // end if valid url?
} // end if url?
//go ahead and download dataURLs right away
if(/^data\:[\w+\-]+\/[\w+\-]+[,;]/.test(payload)){
if(payload.length > (1024*1024*1.999) && myBlob !== toString ){
payload=dataUrlToBlob(payload);
mimeType=payload.type || defaultMime;
}else{
return navigator.msSaveBlob ? // IE10 can't do a[download], only Blobs:
navigator.msSaveBlob(dataUrlToBlob(payload), fileName) :
saver(payload) ; // everyone else can save dataURLs un-processed
}
}//end if dataURL passed?
blob = payload instanceof myBlob ?
payload :
new myBlob([payload], {type: mimeType}) ;
function dataUrlToBlob(strUrl) {
var parts= strUrl.split(/[:;,]/),
type= parts[1],
decoder= parts[2] == "base64" ? atob : decodeURIComponent,
binData= decoder( parts.pop() ),
mx= binData.length,
i= 0,
uiArr= new Uint8Array(mx);
for(i;i<mx;++i) uiArr[i]= binData.charCodeAt(i);
return new myBlob([uiArr], {type: type});
}
function saver(url, winMode){
if ('download' in anchor) { //html5 A[download]
anchor.href = url;
anchor.setAttribute("download", fileName);
anchor.className = "download-js-link";
anchor.innerHTML = "downloading...";
anchor.style.display = "none";
document.body.appendChild(anchor);
setTimeout(function() {
anchor.click();
document.body.removeChild(anchor);
if(winMode===true){setTimeout(function(){ self.URL.revokeObjectURL(anchor.href);}, 250 );}
}, 66);
return true;
}
// handle non-a[download] safari as best we can:
if(/(Version)\/(\d+)\.(\d+)(?:\.(\d+))?.*Safari\//.test(navigator.userAgent)) {
url=url.replace(/^data:([\w\/\-\+]+)/, defaultMime);
if(!window.open(url)){ // popup blocked, offer direct download:
if(confirm("Displaying New Document\n\nUse Save As... to download, then click back to return to this page.")){ location.href=url; }
}
return true;
}
//do iframe dataURL download (old ch+FF):
var f = document.createElement("iframe");
document.body.appendChild(f);
if(!winMode){ // force a mime that will download:
url="data:"+url.replace(/^data:([\w\/\-\+]+)/, defaultMime);
}
f.src=url;
setTimeout(function(){ document.body.removeChild(f); }, 333);
}//end saver
if (navigator.msSaveBlob) { // IE10+ : (has Blob, but not a[download] or URL)
return navigator.msSaveBlob(blob, fileName);
}
if(self.URL){ // simple fast and modern way using Blob and URL:
saver(self.URL.createObjectURL(blob), true);
}else{
// handle non-Blob()+non-URL browsers:
if(typeof blob === "string" || blob.constructor===toString ){
try{
return saver( "data:" + mimeType + ";base64," + self.btoa(blob) );
}catch(y){
return saver( "data:" + mimeType + "," + encodeURIComponent(blob) );
}
}
// Blob but not URL support:
reader=new FileReader();
reader.onload=function(e){
saver(this.result);
};
reader.readAsDataURL(blob);
}
return true;
}; /* end download() */
}));
四、 华为obs二进制下载
var obsClient = new ObsClient({
access_key_id: 'xxx',
secret_access_key: 'xxx',
server: 'xxx'
});
obsClient.getObject({
Bucket : 'vca-resource',
Key : 'upload/我爱你1.mp4',
SaveByType : 'arraybuffer'
}, function (err, result) {
if(err){
console.error('Error-->' + err);
}else{
console.log('Status-->' + result.CommonMsg.Status);
if(result.CommonMsg.Status < 300 && result.InterfaceResult){
// 读取对象字节长度
console.log('Object Length:\n');
console.log(result.InterfaceResult.Content.byteLength);
console.log(result);
this.$downloadToLocal(result.InterfaceResult.Content, "测试123.mp4"); //a标签下载
// downloadVideo(result.InterfaceResult.Content,"测试.mp4")
}
}
});
后端处理
一、后端返回二进制流
const fs = require('fs');
ctx.type = "video/mpeg4";
ctx.body = fs.readFileSync(urls.video);
前端配合
this.$axios({
method: 'get', //请求方法 get post
url: url, //请求地址
// params:params,
// headers:{
// 'Authorization':`Bearer ${getToken()}`
// },
responseType: 'blob' //关键配置项
}).then(res=>{
this.loading = false;
console.log(res);
downloadVideo(res.data,this.resultData.media_name + '.mp4');
})
二、华为云处理
ContentDisposition 设置为 attachment
在前端请求修改 该视频的ContentDisposition
videoUrl = videoUrl.replace("http://resources.bjvca.com","https://vca-resource.obs.cn-north-4.myhuaweicloud.com");
this.$axios({
method:"put",
url:videoUrl + "?metadata=",
headers:{
"Content-Disposition":"attachment",
"x-obs-metadata-directive":"REPLACE_NEW"
}
}).then(res=>{
this.$downloadToLocal(videoUrl,this.resultData.media_name + '.mp4')
})