Title Detailed description of the use of FileReader API for files

Title Detailed description of the use of FileReader API for files

  1. When using it, you should first create a FileReader object.
var fr=new FileReader();

2. Clarify some specific methods of fr read files.

  • readAsDataURL() means to read the content of the file in the format of URL ( commonly used )
  • readAsArrayBuffer() represents the content of the ArryBuffer object
  • readAsBinaryString() represents the original binary data type to represent the file content
  • readAsText() means using a string to represent the content of the file ( commonly used )

3. Clarify some properties of fr

  • error: Indicates an error occurred when reading the file.
  • readyState: Represents the current state of the FileReader object.
  • result: indicates the content of the read file.
  • abort: indicates the operation of terminating file reading

4. Clarify some fr events

  • onabort: called when the reading operation is terminated
  • onerror: called when an error occurs while reading the file
  • onload: called when the read operation is complete
  • onloadend: Called when the read operation is completed, whether it is a successful or failed read. This operation is called after onload and onerror
  • onloadstart: called when the read operation is about to start
  • onprogress: periodically called in the process of reading data

5. Specific case ( code has been commented )

<body>
    <input type="file" id="myfile" onchange="loadfile()">//设置当file读取文件是触发loadfile()函数
    <div id="content"></div>//用来存放读取到的信息
    <script>        
    	//获取标签
    	var myfile=document.getElementById("myfile");        
    	var con=document.getElementById("content");       
 	//引入FileReader
 	var fr=new FileReader();
 	function loadfile(){
    
    
 	//读取input标签的第一个文件            
 	fr.readAsDataURL(myfile.files[0]);
	//当加载成功时,执行该函数
 	fr.onload=function(e){
    
    
 	//e.target.result表示的是读取文件的url信息
 		var str='<img src="'+e.target.result+'">';                
 		con.innerHTML+=str;            
 	    }        
     }    
     </script>
</body>

6. In addition to using FileReader, you can also use window.URL.createObjectURL()
related code

<body>    
	<input type="file" id='myFile' onchange="Fileload()">
	<div id="div"></div>
</body>
<script>    
	var myFile=document.getElementById('myFile');
	var div=document.getElementById('div');    
	function Fileload(){
    
           
       		var url=window.URL.createObjectURL(myFile.files[0]);
        	var str='<img src="'+url+'"/>'
             	div.innerHTML=str;
       }
</script>

The difference between using FIleReader and window.URL.createObjectURL() is: The e.target.result read by FIleReader is base64 encoded and relatively long. But using window.URL.createObjectURL() to read the address, the byte length is relatively short

Guess you like

Origin blog.csdn.net/weixin_47450807/article/details/108554695