Using the file API's FileReader for uploading files

Source: Internet
Author: User

Accessing local files is a headache for browser-based apps, and usually we can only use <input type= "file" > tags to upload files. The implementation process is: When you select a file, the Value property holds the name of the user-specified file, and when the form is submitted, the browser sends the contents of the selected file to the server, not just the file name. Then get the address returned by the server and do a preview.

But if one day we want to upload a picture, pass the picture after the preview wants to change another picture, then must first upload to the server again to preview. In the case of slow network, this really is very frustrating.

So we need to preview and upload to the server at some point, especially if there is a need for cutting functions, such as the avatar replacement of Sina Weibo. But the only thing we can do now is to develop or use Flash with plug-ins, and because of the different technical implementations of various browsers, our program becomes very complex and difficult to maintain in order to enable the program to support multiple browsers. Fortunately, the file API is now available.

By listening to the Change event we know the file that the user has selected, and we have added a Files collection that will contain the file object, each of which corresponds to a document. And both have the following read-only attribute name,size,type,lastmodifieddate.

To <input type= "file" name= "file" id= "Postfile" > For example, Monitor onchange to print its file object:

?

This allows us to know some information about the file format, file name, size, and so on, which the user chooses. Therefore, it is very easy for us to validate the selected documents to determine whether they meet some of our requirements.

In addition, the file API provides the FileReader type to read the data in the files.

The FileReader type implements an asynchronous file-reading mechanism, similar to XMLHttpRequest, but it reads a file system instead of a remote server. Several reading methods are available:

Readastext (file,encoding): reads the file as plain text, saves the read text in the result property, and the second parameter specifies the encoding type, optional.

Readasdataurl (file): The read file is stored as a data URL in the result property.

Readasbinarystring (file): reads the file and saves a string in the result property.

Readasarraybuffer (file): reads a file and saves a arraybuffer containing the file's contents in the Result property

The same local image is read by the above method, and the information stored in the result property is printed in comparison with the following:

Readastext (file,encoding):

Readasdataurl (file):

By comparing the above, we find that the method of reading the files provides a great convenience for the flexible processing of file data. For example, read the image file and save as a data URL, you can do pre-upload preview function.

Because the read process is asynchronous, there are several events in the FileReader that handle different situations: progress (whether new data is read), Erro (whether an error has occurred), load (whether the entire file has been read).

An error event is triggered when a file cannot be read for various reasons, and an attribute code (error code) is stored in an object in the error property of FileReader when the error event is triggered.

Examples of uploading previews using FileReader:

Html:

<label class= "Item_label" > Upload Photo: <span style= "width:100px; height:100px;border:1px solid #ccc; Display:inline-block "></span><input type= "File" name= "file" id= "Postfile" style= "WIDTH:74PX;" ><span id= "Error_text" style= "Display:none;" > Tips </span></label>

  

Javascript:

document.getElementById (' Postfile '). onchange = function () {var val = This.value;var Uploadtype = '. Jpg,.gif,.bmp,.png ' ;//['. jpg ', '. gif ', '. bmp ', '. png ']; The format can be uploaded var Fileext = Val.substr (Val.lastindexof (".")). toLowerCase (); Extracts the last occurrence from a string, and converts the character to lowercase var result = Uploadtype.indexof (Fileext); Find if the suffix name matches the condition, if the return >=0 is met, a negative number is returned if it is not met, _alertmsg = $ (' #error_text '), var ofreader = new FileReader (); This.files.length = = = 0) {return;} var ofile = this.files[0]; If there is only one file, only the first element in the FileList object needs to be accessed. if (ofile.size/1024 <) {_alertmsg.html ("<font style= ' Color:blue ' >√ </font> "). Show ()};if (Result < 0) {_alertmsg.html (" Please enter the correct format: "+ Uploadtype). Show (); Else{_alertmsg.html ("<font style= ' Color:blue ' >√</font>"). Show ();};o Freader.readasdataurl (ofile); Begins a read operation in the background. When all the contents of the image file are loaded, they are converted into a data:url, passed to the onload callback function ofreader.onload = function (ofrevent) {// Called when the read operation completed successfully. document.getElementById ("Uploadpreview"). src = OFREvent.target.result;};};

  

Effect as well as the returned picture URL:

Using the file API's FileReader for uploading files

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.