JS端基于download.js实现图⽚、视频时直接下载⽽不是打开预览
项⽬中的附件列表,通常情况都需要提供下载、删除的功能,功能本⾝没有什么要说的,都是基本功能,使⽤浏览器的的下载功能,也都是⽤window.open(url),或者window.location.href=url的⽅式,url 即为附件下载接⼝,浏览器⾃动解析,如果是图⽚、视频、txt等格式的会直接预览⽂件,⽽不是像docx、xlsx⼀样直接下载,项⽬中为了功能明确,将预览单独加了⼀个查看按钮,下载按钮要实现⽆论什么⽂件格式都直接下载。
js arguments有两种⽅式处理:
⼀.后台接⼝层⾯处理:(⽐较常见)
响应头中添加标识:
Response.AddHeader("Content-Disposition", "attachment; filename=" +
HttpUtility.UrlEncode(annotation.FileName, System.Text.Encoding.UTF8));
添加后,浏览器就会全都直接下载,不区分⽂件格式
⼆.前端JS使⽤XMLHttpRequest结合download.js处理
1)⾸先页⾯中需要引⽤download.js
2)公共⽅法
/*
* 使⽤download.js 强制浏览器下载图⽚、视频等⽂件
* @param {any} url url链接地址
* @param {any} strFileName ⽂件名
* @param {any} strMimeType ⽂件类型
* dzl
* 2020年5⽉8⽇
*/
function downloadfile(url, strFileName, strMimeType) {
var xmlHttp = null;
if (window.ActiveXObject) {
// IE6, IE5 浏览器执⾏代码
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} else if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari 浏览器执⾏代码
xmlHttp = new XMLHttpRequest();
}
//2.如果实例化成功,就调⽤open()⽅法:
if (xmlHttp != null) {
xmlHttp.open("get", url, true);
xmlHttp.send();
}
function doResult() {
if (adyState == 4) { //4表⽰执⾏完成
if (xmlHttp.status == 200) { //200表⽰执⾏成功
sponse, strFileName, strMimeType);
}
}
}
}
注意: sponseType = 'blob';是关键,必须要设置
3)下载按钮点击事件中调⽤公共⽅法
downloadfile(url, filename, getFileType(filename))
附上根据⽂件名的尾缀返回⽂件类型的公共⽅法:
/*
* 根据⽂件名的尾缀返回⽂件类型
* @param {any} fileName ⽂件名
* dzl
* 2020年5⽉9⽇
*/
function getFileType(fileName) {
// 后缀获取
let suffix = '';
// 获取类型结果
let result = '';
try {
const flieArr = fileName.split('.');
suffix = flieArr[flieArr.length - 1];
} catch (err) {
suffix = '';
}
// fileName⽆后缀返回 false
if (!suffix) { return false; }
suffix = LocaleLowerCase();
// 图⽚格式
const imglist = ['png', 'jpg', 'jpeg', 'bmp', 'gif'];
// 进⾏图⽚匹配
result = imglist.find(item => item === suffix);
if (result) {
return 'image';
}
// 匹配txt
const txtlist = ['txt'];
result = txtlist.find(item => item === suffix);
if (result) {
return 'txt';
// 匹配 excel
const excelist = ['xls', 'xlsx'];
result = excelist.find(item => item === suffix);
if (result) {
return 'excel';
}
// 匹配 word
const wordlist = ['doc', 'docx'];
result = wordlist.find(item => item === suffix);
if (result) {
return 'word';
}
// 匹配 pdf
const pdflist = ['pdf'];
result = pdflist.find(item => item === suffix);
if (result) {
return 'pdf';
}
// 匹配 ppt
const pptlist = ['ppt', 'pptx'];
result = pptlist.find(item => item === suffix);
if (result) {
return 'ppt';
}
// 匹配视频
const videolist = ['mp4', 'm2v', 'mkv', 'rmvb', 'wmv', 'avi', 'flv', 'mov', 'm4v'];
result = videolist.find(item => item === suffix);
if (result) {
return 'video';
}
// 匹配⾳频
const radiolist = ['mp3', 'wav', 'wmv'];
result = radiolist.find(item => item === suffix);
if (result) {
return 'radio';
}
/
/ 其他⽂件类型
return 'other';
}
download.js源码
//download.js v4.21, by dandavis; 2008-2018. [MIT] see danml/download.html for tests/usage
// v1 landed a FF+Chrome compatible way of downloading strings to local un-named files, upgraded to use a hidden frame and optional mime
// v2 added named files via a[download], msSaveBlob, IE (10+) support, and window.URL support for larger+faster saves than dataURLs
// v3 added dataURL and Blob Input, bind-toggle arity, and legacy dataURL fallback was improved with force-download mime and base64 support. 3.1 improved safari handling. // v4 adds AMD/UMD, commonJS, and plain browser support
// v4.1 adds url download capability via solo URL argument (same domain/CORS only)
// v4.2 adds semantic variable names, long (over 2MB) dataURL support, and hidden by default temp anchors
// github/rndme/download
(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 ports,
// like Node.
} 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
defaultMime = "application/octet-stream", // this default mime also triggers iframe downloads
mimeType = strMimeType || defaultMime,
payload = data,
url = !strFileName && !strMimeType && payload,
anchor = ateElement("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", "l") 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);
download(sponse, 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);
pe || 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
}
}else{//not data url, is it a string with special needs?
if(/([ 80- ff])/.test(payload)){
var i=0, tempUiArr= new Uint8Array(payload.length), mx=tempUiArr.length;
for(i;i<mx;++i) tempUiArr[i]= payload.charCodeAt(i);
payload=new myBlob([tempUiArr], {type: mimeType});
}
blob = payload instanceof myBlob ?
payload :
new myBlob([payload], {type: mimeType}) ;
function dataUrlToBlob(strUrl) {
var parts= strUrl.split(/[:;,]/),
type= parts[1],
indexDecoder = strUrl.indexOf("charset")>0 ? 3: 2,
decoder= parts[indexDecoder] == "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 = "";
anchor.style.display = "none";
anchor.addEventListener('click', function(e) {
e.stopPropagation();
});
document.body.appendChild(anchor);
setTimeout(function() {
anchor.click();
veChild(anchor);
if(winMode===true){setTimeout(function(){ vokeObjectURL(anchor.href);}, 250 );}
}, 66);
return true;
}
/
/ handle non-a[download] safari as best we can:
if(/(Version)\/(\d+)\.(\d+)(?:\.(\d+))?.*Safari\//.test(navigator.userAgent)) {
if(/^data:/.test(url)) url="data:"+place(/^data:([\w\/\-\+]+)/, defaultMime);
if(!window.open(url)){ // popup blocked, offer direct download:
if(confirm("Displaying New Document\n\nUse to download, then click back to return to this page.")){ location.href=url; }
}
return true;
}
//do iframe dataURL download (old ch+FF):
var f = ateElement("iframe");
document.body.appendChild(f);
if(!winMode && /^data:/.test(url)){ // force a mime that will download:
url="data:"+place(/^data:([\w\/\-\+]+)/, defaultMime);
}
f.src=url;
setTimeout(function(){ veChild(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(ateObjectURL(blob), true);
}else{
// handle non-Blob()+non-URL browsers:
if(typeof blob === "string" || structor===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();
sult);
};
}
return true;
}; /* end download() */
}));
js⽂件下载插件介绍和使⽤⽅法 download.js
在前端想要⽣成txt或者其他格式⽂件来保存⼀些数据,或者在数据请求服务器成功后想要将数据⽣成⽂件并下载,这些需求还是⽐较多的,这⾥使⽤到的download.js。既可以满⾜这些需求。第⼀步:下载
1.下载可以在官⽹上进⾏下载原⽹址:download
2.js
2.也可以使⽤我上传的资源(下载与上述官⽹) 免费哦!下载
第⼆步:引⽤
1.将下载的⽂件放在项⽬中,并使⽤ <script src="./download
2.js"></script> 进⾏引⽤ (速度快)
2.使⽤⽹络引⽤ <script src="danml/js/download2.js"></script>
第三步:开始使⽤
//⽣成⼀个txt的⽂件,讲字符串变量 str 的内容放在⾥⾯,并完成下载
var str = "hello world可以中⽂吗?答案:可以的";
download(str, "", "text/plain");
/
/也将⽣成⼀个txt⽂件,和上⾯的结果是⼀摸⼀样
str = "data:text/plain,hello%20world";
download(str, "", "text/plain");
//将数组或者json对象写⼊到⽂件中
var debug = {hello : "world"};
var blob = new Blob([JSON.stringify(debug, null, 2)]);
download(blob, "", "text/plain");
var str= "hello world", arr= new Uint8Array(str.length);
str.split("").forEach(function(a,b){
arr[b]=a.charCodeAt();
});
download( arr, "", "text/plain" );
//将html页⾯中的⼀部分⽣成单独的 html⽂档
download(document.body.outerHTML, "dlHTML.html", "text/html");
//给字符串添加标签,或者html⽚段直接给⽅法,将会⽣成对应内容的⽂件
download(new Blob(["hello world".bold()]), "dlHtmlBlob.html", "text/html");
//将ajax查询回来的结果,赋值给⽂件,并下载
$.ajax({
url: "/download.html",
success: download.bind(true, "text/html", "dlAjaxCallback.html")
});
//将图⽚的base64装⼊到图⽚中并下载。
download("data:image/gif;base64,R0lGODlhRgAVAIcAAOfn5+/v7/f39//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //使⽤xhr获取本域名下⽂件,并封装到⽂件进⾏下载。这⾥的前提是xhr访问的⽂件必须和该程序执⾏在同⼀域名下,
//否则会报跨域的问题。⽐如此程序执⾏在localhost下⾯,⽽这⾥的访问地址使⽤的是danml,就会访问不成功。
var x=new XMLHttpRequest();
x.open("GET", "danml/wave2.gif", true);
x.οnlοad=function(e){
sponse, "dlBinAjax.gif", "image/gif" );
};
x.send();
扩展:还可以使⽤⽂件上传再下载进⾏测试。
<input id="file" type="file" οnchange="download(this.files[0], this.files[0].name, this.files[0].type)">
以上就是JS端基于download.js实现图⽚、视频时直接下载⽽不是打开预览的详细内容,更多关于js实现图⽚、视频时直接下载的资料请关注其它相关⽂章!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论