JavaScript File API File Upload preview, api File Upload

Source: Internet
Author: User

JavaScript File API File Upload preview, api File Upload

For browser-based applications, accessing local files is a headache. What we can do is to use<Input type = "file">To upload files. The implementation process is as follows: when a file is selected, the value Attribute stores the name of the file specified by the user, and when the form is submitted, the browser sends the content of the selected file to the server, not just the file name. Obtain the address returned by the server, and then Preview It.

However, if one day we want to upload an image and preview the image and want to change it to another image, we have to upload it to the server before previewing. When the network is slow, this is really a tough task.

So sometimes we need to preview and upload the image to the server, especially for some scenarios with cutting functions, such as changing the profile picture on Sina Weibo. However, currently, you can only use plug-ins to develop or use flash. Because different browser technologies have different implementations, in order to allow the program to support multiple browsers, our programs will become very complex and difficult to maintain. Fortunately, now we haveFile API.

By listening to the change event, we can know the selected file and add a set of files, which contains the file object. Each file object corresponds to a file. The following read-only attributes are available: name, size, type, and lastModifiedDate.

To<Input type = "file" name = "file">For example, monitor the onchange event to print its file object:

  

We can learn some information about the selected file format, file name, file size, and so on. Therefore, we can easily verify the selected files to determine whether they meet our specific requirements.

In addition, the File API also provides the FileReader type to read data from files.

The FileReader type implements an asynchronous file reading mechanism, similar to XMLHttpRequest, But It reads the file system rather than the remote server. It also provides several reading methods:

  • ReadAsText (file, encoding): reads a file in plain text format and stores the read text in the result attribute. The second parameter is used to specify the encoding type. Optional.
  • ReadAsDataURL (file): Read files are saved as data URLs in the result attribute.
  • ReadAsBinaryString (file): Read the file and save a string in the result attribute.
  • ReadAsArrayBuffer (file): Read the file and save an ArrayBuffer that contains the file volume in the result attribute.

Read the same local image by using the above methods, and print the information stored in the result attribute for comparison as follows:

ReadAsText (file, encoding ):

ReadAsDataURL (file ):

Through the comparison above, we found that these file reading methods provide great convenience for flexible file data processing. For example, if you want to read an image file and save it as a Data url, You can preview the file before upload.

Since the read process is asynchronous, several events in the FileReader process different situations: progress (whether new data is read) and erro (whether an error occurs) and load (whether the entire file has been read ).

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

Example of using FileReader for upload preview:

HTML:

<Label class = "item_label"> upload a 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; "> prompt </span> </label>

JavaScript:

Document. getElementById ('postfile '). onchange = function () {var val = this. value; var upLoadType = '.jpg, .gif, .bmp, .png '; // your '.jpg', '.gif ', '.bmp', '.png ']; // The format of var fileExt = val. substr (val. lastIndexOf (". ")). toLowerCase (); // extract the last appearance from the string. and convert it to lowercase var result = upLoadType. indexOf (fileExt); // check whether the suffix name meets the condition. If yes, return> = 0. If not, return a negative number; _ alertMsg =$ ('# error_text '); var oFReader = new FileReader (); if (t His. files. length = 0) {return;} var oFile = this. files [0]; // if there is only one file, you only need to access the first element in the FileList object. if (oFile. size/1024 <100) {_alertMsg.html ("<font style = 'color: blue '> √ </font> "). show ()}; if (result <0) {_alertMsg.html ("enter the correct format:" + upLoadType ). show ();} else {_alertMsg.html ("<font style = 'color: blue '> √ </font> "). show () ;}; oFReader. readAsDataURL (oFile); // starts reading data in the background. After all the content of the image file is loaded, it is converted into a data: URL and transmitted to the oFReader In the onload callback function. onload = function (oFREvent) {// called when the read operation is completed successfully. document. getElementById ("uploadPreview "). src = oFREvent.tar get. result ;};};

Effect and returned image URL:

The above is all the content of this article, hoping to help you learn.

Articles you may be interested in:
  • JQuery plug-in jcrop + Fileapi perfectly implements Image Upload + cropping + preview code sharing
  • JavaScript File API for File upload Preview

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.