Get the file
If you want to get files on the user's computer in the web, the method we usually use is to use a form element<input type="file">
Operates the file selected by the user.
We can listen to the element in jschange
Events get file information, usually the file will be stored in the element.files
In the collection, for example:
<input type="file"> <script> const files = ('input'); ('change',(e)=>{ (); }) </script>
File object
File
There are mainly the following commonly used properties in the object, and they are all read-only properties.
-
name
: File name in the system. -
size
: File size (units in bytes). -
type
: The MIME type of the file. -
lastModified
: The last time of file modification.
Through the basic information of these files, we can basically filter or verify the selected files, such as:
function validateFile(file){ const maxSize = 1 * 1024 * 1024; const types = ['.jpg','.jpeg','.png','.bmp','.webp','.gif']; const fileName = (); if( > maxSize){ alert('The file is too large! '); return false; } if(!((item)=>(item))){ alert('File type does not match! '); return false; } return true; } ('change',(e)=>{ if(!validateFile([0])){ = ''; return; } // Follow-up operations...})
In the above code, we use a function to determine whether the file we selected meets the requirements for the next operation. The mainfile
The properties on the object determine whether the file size and type meet the requirements. Through different functions, we can filter out files that do not meet our expectations.
existFile
The object does not contain the content information of the file, but usually we get itFile
The purpose of file information on the object is to read the real file data information, and then another API needs to be used:FileReader
。
FileReader
FileReader
It is an API provided in js for reading file data. It can read file data from the local file system, and its reading process is carried out asynchronously.
Common methods of FileReader objects:
-
readAsDataURL
: This method can read the file and convert its content data into a data URL, and store the result toFileReader
Exampleresult
Attributes. -
readAsText
: Read the plain text content of the file, and the same result is stored inFileReader
Exampleresult
Attributes. -
readAsBinaryString
: Read the binary information of the file, and the same result is stored inFileReader
Exampleresult
Attributes.
Since the process of reading files is asynchronous, we mainly useFileReader
The listening events provided to obtain file information, there are three commonly used events:
-
load
: The file is fired after it is loaded successfully, and it can be passedresult
Attributes get file information. -
progress
: File reading progress information, each50ms
Triggered once, attributes andXHR
Similar in. -
error
: Triggered when a file read error occurs, iferror
Event triggerload
Events will not be triggered. existerror
After triggering, it can be passed on the instanceerror
The attribute obtains the error message, which contains an information code, which represents: 1 (file not found), 2 (safety error), 3 (read interrupted), 4 (file not read), and 5 (encoding error).
Suppose we need to read an image and display it to the page, we can do the following:
const files = ('input'); const img = ('img'); ('change',(e)=>{ let file = [0]; // Verify the basic information of the file if(!validateFile(file)){ = ''; return; } let reader = new FileReader(); (file); // Read out the file information and convert it into a URL ('load',(e)=>{ ('File loading is complete'); = ; // Assign the URL to the img element, it is the reader at this time }) })
File upload
How will we upload the file after we get it on the client? Uploading files to the server will inevitably involve network communication, and if you conduct network communication in js, you will naturally use ajax.
File upload using XHR
We only need to think of forming ahttp
The message will naturally specify how to write the code.http
The request mainly includes three parts: request line, request header, and request body. For example, I need to implement the followinghttp
Message:
POST /upload HTTP/1.1 Host:127.0.0.1:5000 Content-Type: multipart/form-data;boundary=xxx ---xxx Content-Disposition:form-data; name="xxhh";filename="" Content-Type:image/jpeg File data... --xxx--
We can implement it through the following js
const xhr = new XMLHttpRequest(); ('POST','http://127.0.0.1:5000/upload'); const form = new FormData(); ('xxhh',file,''); // The first parameter corresponds to the name in Content-Disposition// The second parameter is file data (here is the real data of the file and not the File object)// The third is the filename in Content-Disposition, which defaults to the local file name(form); = ()=>{ (); //Get the response result}
We passedopen
Construct the request header information and passFormData
This API makes it easier for us to write request body information, which will automatically set our request header information toContent-Type: multipart/form-data;
And automatically generate oneboundary
,useappend
The method can add a field information to it and finally call it(form)
A request carrying data is issued.
The above is the detailed explanation of the code that JS obtains local files and transmits networks. For more information about JS obtains local files and transmits, please pay attention to my other related articles!