如何用在瀏覽器端預(yù)覽本地文件?
今天的主題是使用瀏覽器預(yù)覽本地文件。
由于瀏覽器安全策略的限制,javascript程序不能自由地訪問本地資源,這是對(duì)用戶信息安全來說,是一項(xiàng)不得不遵守的準(zhǔn)則。假如網(wǎng)絡(luò)上的javascript程序可以自如地訪問用戶主機(jī)的本地資源,那么瀏覽器用戶將毫無安全可言。盡管有這個(gè)安全限制,但是在得到用戶允許的情況下,瀏覽器還是可以訪問本地資源的。
獲得用戶允許的方法就是通過標(biāo)簽來讓用戶手動(dòng)選擇文件,這一過程就是用戶授予訪問權(quán)限的過程。然后 使用獲得File 對(duì)象通過URL.createObjectURL(file)轉(zhuǎn)換為文件url, 就可以傳遞給類似y于img,video,audio等標(biāo)簽使用了。我將本地文件轉(zhuǎn)換為url 的功能封裝成了一個(gè)類。
function LocalFileUrl(){ var _this = this; this.input_id = 'input_getLocalFile'+ Math.round(Math.random() * 1000); $("body").append("<input type='file' style='display:none' id='"+this.input_id+"' multiple>"); this.urls=[]; var _this = this; $("#" + this.input_id).change(function(e){ console.log("change"); //如果_this.urls 不為空,則釋放url if(_this.urls){ _this.urls.forEach(function(url,index,array){ URL.revokeObjectURL(url.url);//一經(jīng)釋放,馬上將無法使用這個(gè)url的資源 }); _this.urls = []; } $(this.files).each(function(index,file){ var url = URL.createObjectURL(file); _this.urls.push({url:url,file:file}); }); typeof _this.getted == 'function' && _this.getted(_this.urls); })}/*參數(shù)說明:getted:function(urls){}urls是一個(gè)url對(duì)象數(shù)組。[url]url = {url:url, //選取的文件urlfile:file //選取的文件對(duì)象引用}*/LocalFileUrl.prototype.getUrl = function(getted){ this.getted = getted; $("#"+ this.input_id).click();}使用方法:
var localFileUrl = new LocalFileUrl();//實(shí)例化對(duì)象//觸發(fā)讀取,彈出文件選擇框,并且監(jiān)聽文件選擇事件。 localFileUrl.getUrl(function(urls){ urls.forEach(function(item,index,array){ $("body").append("<div>"+index+"----"+item.url+"</div>") })})使用jQuery 的promise對(duì)象改寫
這種方式的好處是可以使用鏈?zhǔn)綄懛ǎ⑶铱梢越壎ǘ鄠€(gè)done事件處理函數(shù),執(zhí)行順序按照綁定順序。
function LocalFileUrl(){ this.dtd ={}; this.input_id = 'input_getLocalFile'+ Math.round(Math.random() * 1000); $("body").append("<input type='file' style='display:none' id='"+this.input_id+"' multiple>"); this.urls=[]; var _this = this; $("#" + this.input_id).change(function(e){ //如果_this.urls 不為空,則釋放url if(_this.urls){ _this.urls.forEach(function(url,index,array){ URL.revokeObjectURL(url.url);//一經(jīng)釋放,馬上將無法使用這個(gè)url的資源 }); _this.urls = []; } $(this.files).each(function(index,file){ var url = URL.createObjectURL(file); _this.urls.push({url:url,file:file}); }); //傳入一個(gè)可選的參數(shù)數(shù)組 _this.dtd.resolveWith(window,new Array(_this.urls)); })}/*返回一個(gè)jquery 的promise 對(duì)象,可以綁定done()事件。done(urls)接收一個(gè)urls數(shù)組{ url:url, file:file// 選取的文件對(duì)象}*/LocalFileUrl.prototype.getUrl = function(){ this.dtd = $.Deferred(); $("#"+ this.input_id).click(); return this.dtd.promise();}
新聞熱點(diǎn)
疑難解答
圖片精選