English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Beispielcode zum Lesen lokaler Dateien mit JavaScript

How to preview local files on the browser side?

Today's topic is to preview local files using the browser.

Due to the restrictions of browser security policies, JavaScript programs cannot freely access local resources, which is a principle that must be followed for user information security. If JavaScript programs on the network could freely access the local resources of the user's host, then the browser users would have no security at all. Although there is this security restriction, the browser can still access local resources with the user's permission.

The method to obtain user permission is to let the user manually select files through tags, which is the process of the user granting access permissions. Then, using the obtained File object, it can be converted to a file URL through URL.createObjectURL(file), which can then be passed to tags like img, video, audio, etc. I have encapsulated the function of converting local files to URLs into a class.

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");
  //If _this.urls is not empty, release the url
  if(_this.urls){
   _this.urls.forEach(function(url, index, array){
    URL.revokeObjectURL(url.url);//Once released, the resource at this url will no longer be usable
   });
   _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);
 })
}
/*
Parameter description: getted: function(urls) {
urls is an array of URL objects. [url]
url = {
url:url //Selected file URL
file:file //Reference to the selected file object
}
*/
LocalFileUrl.prototype.getUrl = function(getted) {
 this.getted = getted;
 $("#"+ this.input_id).click();
}

Usage method:

var localFileUrl = new LocalFileUrl();//Instantiate the object
//Trigger the read operation, pop up the file selection dialog, and listen to the file selection event.  
localFileUrl.getUrl(function(urls) {
 urls.forEach(function(item,index,array){
  $("body").append("<div>"+index+"----"+item.url+"</div>"
 })
})

Rewritten using jQuery's promise object

The advantage of this method is that it can use chained syntax and bind multiple done event handlers, with the execution order following the binding order.

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){
  //If _this.urls is not empty, release the url
  if(_this.urls){
   _this.urls.forEach(function(url, index, array){
    URL.revokeObjectURL(url.url);//Once released, the resource at this url will no longer be usable
   });
   _this.urls = [];
  }
  $(this.files).each(function(index, file){
   var url = URL.createObjectURL(file);
   _this.urls.push({url: url, file: file});
  });
  //Pass an optional array of parameters
  _this.dtd.resolveWith(window, new Array(_this.urls));
 })
}
/*
Returns a jQuery promise object that can bind the done() event. The done(urls) method accepts an array of urls
}
 url:url
 file:file// 选取的文件对象
}
*/
LocalFileUrl.prototype.getUrl = function(){
 this.dtd = $.Deferred();
 $("#"+ this.input_id).click();
 return this.dtd.promise();
}

使用方式

var localFilrUrl = new LocalFileUrl();
// 绑定done事件
localFileUrl.getUrl().done(function(urls){
 urls.forEach(function(item,index,array){
  $("body").append("<div>"+index+"----"+item.url+"</div>"
 })
}).done(function(){
 console.log("完成");
}).done(function(){
 alert("已经读取了本地文件路径");
})

兼容性

URL.createObjectURL(File/Blob)是一个实验性的功能。IE10及以上版本兼容与之对应的是URL.revokeObjectURL(url),它用来告诉浏览器已经不需要这个url的引用了,可以释放掉了。一经调用,这个url立即失效。

声明:本文内容来源于网络,版权归原作者所有。内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#oldtoolbag.com(在发邮件时,请将#更换为@进行举报,并提供相关证据。一经查实,本站将立即删除涉嫌侵权内容。)

Gefällt mir