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

Example of Reading Local Files Using JavaScript

How to preview local files on the browser side?

Today's topic is how 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 can freely access the local resources of the user's host, then the browser users will have no security to speak of. 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 users manually select files through tags, which is the process of users granting access permissions. Then, using the obtained File object, convert it to a file URL through URL.createObjectURL(file), which can be passed to tags like img, video, audio, etc. I 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 cannot be used immediately
   });
   _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();//Instance 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 handling functions, 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 cannot be used immediately
   });
   _this.urls = [];
  }
  $(this.files).each(function(index, file){
   var url = URL.createObjectURL(file);
   _this.urls.push({url: url, file: file});
  });
  //An optional array of parameters can be passed in
  _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// Selected file object
}
*/
LocalFileUrl.prototype.getUrl = function(){
 this.dtd = $.Deferred();
 $("#"+ this.input_id).click();
 return this.dtd.promise();
}

Usage

var localFilrUrl = new LocalFileUrl();
// Binding done event
localFileUrl.getUrl().done(function(urls){
 urls.forEach(function(item,index,array){
  $("body").append("<div">"+index+"----"+item.url+"</div>")
 )
}).done(function(){
 console.log("Completed");
}).done(function(){
 alert("The local file path has been read");
)

Compatibility

URL.createObjectURL(File/(Blob) is an experimental feature.IE10and above versions are compatibleThe corresponding function is URL.revokeObjectURL(url), which tells the browser that the reference to this url is no longer needed and can be released. Once called, this url will immediately become invalid.

Declaration: The content of this article is from the network, the copyright belongs to the original author, the content is contributed and uploaded by Internet users spontaneously, this website does not own the copyright, does not undergo artificial editing, and does not assume relevant legal liability. If you find content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (When reporting via email, please replace # with @) for reporting violations, and provide relevant evidence. Once verified, this site will immediately delete the content suspected of infringement.

You May Also Like