Home Web Front-end JS Tutorial How to read local files in js

How to read local files in js

Jun 19, 2018 am 10:19 AM
js read

Below I will share with you an example of js reading local files. It has a good reference value and I hope it will be helpful to everyone.

How to preview local files in the browser?

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

Due to the restrictions of browser security policies, JavaScript programs cannot freely access local resources. This is a guideline 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 browser users will have no security at all. Despite this security restriction, the browser can still access local resources with the user's permission.

The way to obtain the user's permission is to let the user manually select the file through the label. This process is the process of the user granting access permissions. Then use the obtained File object to convert it into a file URL through URL.createObjectURL(file), which can be passed to tags such as img, video, audio, etc. for use. I encapsulated the function of converting local files into URLs into a class.

function LocalFileUrl(){
 var _this = this;
 this.input_id = 'input_getLocalFile'+ Math.round(Math.random() * 1000);
 $("body").append("<input type=&#39;file&#39; style=&#39;display:none&#39; id=&#39;"+this.input_id+"&#39; 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);//一经释放,马上将无法使用这个url的资源
   });
   _this.urls = [];
  }
  $(this.files).each(function(index,file){
   var url = URL.createObjectURL(file);
   _this.urls.push({url:url,file:file});
  });
  typeof _this.getted == &#39;function&#39; && _this.getted(_this.urls);
 })
}
/*
参数说明:getted:function(urls){}
urls是一个url对象数组。[url]
url = {
url:url, //选取的文件url
file:file //选取的文件对象引用
}
*/
LocalFileUrl.prototype.getUrl = function(getted){
 this.getted = getted;
 $("#"+ this.input_id).click();
}
Copy after login

Usage method:

var localFileUrl = new LocalFileUrl();//实例化对象
//触发读取,弹出文件选择框,并且监听文件选择事件。  
localFileUrl.getUrl(function(urls){
 urls.forEach(function(item,index,array){
  $("body").append("<p>"+index+"----"+item.url+"</p>")
 })
})
Copy after login

Use jQuery’s promise object to rewrite

This way The advantage is that you can use chain writing, and you can bind multiple done event processing functions, and the order of execution is according to the binding order.

function LocalFileUrl(){
 this.dtd ={};
 this.input_id = &#39;input_getLocalFile&#39;+ Math.round(Math.random() * 1000);
 $("body").append("<input type=&#39;file&#39; style=&#39;display:none&#39; id=&#39;"+this.input_id+"&#39; 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);//一经释放,马上将无法使用这个url的资源
   });
   _this.urls = [];
  }
  $(this.files).each(function(index,file){
   var url = URL.createObjectURL(file);
   _this.urls.push({url:url,file:file});
  });
  //传入一个可选的参数数组
  _this.dtd.resolveWith(window,new Array(_this.urls));
 })
}
/*
返回一个jquery 的promise 对象,可以绑定done()事件。done(urls)接收一个urls数组
{
 url:url,
 file:file// 选取的文件对象
}
*/
LocalFileUrl.prototype.getUrl = function(){
 this.dtd = $.Deferred();
 $("#"+ this.input_id).click();
 return this.dtd.promise();
}
Copy after login

How to use

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

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

JS plug-in for Web forms (high-quality recommendation)

How to implement online customer service function in jQuery

How to use the image viewing plug-in in jQuery

The above is the detailed content of How to read local files in js. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to read txt file correctly using pandas How to read txt file correctly using pandas Jan 19, 2024 am 08:39 AM

How to use pandas to read txt files correctly requires specific code examples. Pandas is a widely used Python data analysis library. It can be used to process a variety of data types, including CSV files, Excel files, SQL databases, etc. At the same time, it can also be used to read text files, such as txt files. However, when reading txt files, we sometimes encounter some problems, such as encoding problems, delimiter problems, etc. This article will introduce how to read txt correctly using pandas

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

Practical tips for reading txt files using pandas Practical tips for reading txt files using pandas Jan 19, 2024 am 09:49 AM

Practical tips for reading txt files using pandas, specific code examples are required. In data analysis and data processing, txt files are a common data format. Using pandas to read txt files allows for fast and convenient data processing. This article will introduce several practical techniques to help you better use pandas to read txt files, along with specific code examples. Reading txt files with delimiters When using pandas to read txt files with delimiters, you can use read_c

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

Example of reading and writing CSV files using OpenCSV in Java Example of reading and writing CSV files using OpenCSV in Java Dec 20, 2023 pm 01:39 PM

Example of using OpenCSV to read and write CSV files in Java. CSV (Comma-SeparatedValues) refers to comma-separated values ​​and is a common data storage format. In Java, OpenCSV is a commonly used tool library for reading and writing CSV files. This article will introduce how to use OpenCSV to implement examples of reading and writing CSV files. Introducing the OpenCSV library First, you need to introduce the OpenCSV library to

How to create a stock candlestick chart using PHP and JS How to create a stock candlestick chart using PHP and JS Dec 17, 2023 am 08:08 AM

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

Practical methods for reading web page data with Pandas Practical methods for reading web page data with Pandas Jan 04, 2024 am 11:35 AM

The practical method of reading web page data in Pandas requires specific code examples. During data analysis and processing, we often need to obtain data from web pages. As a powerful data processing tool, Pandas provides convenient methods to read and process web page data. This article will introduce several commonly used practical methods for reading web page data in Pandas, and attach specific code examples. Method 1: Use the read_html() function. Pandas’ read_html() function can read directly from the web page.

Pandas usage tutorial: Quick start for reading JSON files Pandas usage tutorial: Quick start for reading JSON files Jan 13, 2024 am 10:15 AM

Quick Start: Pandas method of reading JSON files, specific code examples are required Introduction: In the field of data analysis and data science, Pandas is one of the important Python libraries. It provides rich functions and flexible data structures, and can easily process and analyze various data. In practical applications, we often encounter situations where we need to read JSON files. This article will introduce how to use Pandas to read JSON files, and attach specific code examples. 1. Installation of Pandas

See all articles