JavaScript file API files upload Preview _javascript tips

Source: Internet
Author: User

Accessing local files is a headache for browser-based applications, and usually all we can do is upload files using <input type= "file" > tags. The implementation process is: When the file is selected, 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 rather than just sending 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, the picture after the preview to change another picture, we have to upload to the server and then preview. In the slow network situation, this really is very frustrating.

So we sometimes need to preview and upload to the server, especially some of the need for cutting functions, such as Sina Weibo's avatar replacement. But the only thing that can be done is to develop or use flash with plug-ins, because the technology of different browsers is not the same, in order to enable the program to support multiple browsers, our program will become very complex and difficult to maintain. Fortunately, we now have the File API.

By listening to the change event, we can learn about the files that the user chooses, and add a Files collection that contains the file object, each of which corresponds to one. And all have the following read-only property name,size,type,lastmodifieddate.

Take the <input type= "file" name= "file" > for example, monitor the onchange to print its file object:

  

From this we can learn some information about the file format, filename, file size, etc. that the user chooses. So it is very easy for us to make a verification of the selected documents to meet some of our requirements.

In addition, the file API provides the FileReader type to read data from a file.

FileReader type Implementation an asynchronous file-reading mechanism, similar to XMLHttpRequest, but it reads a file system rather than a remote server. And several reading methods are provided:

    • 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): Read files are stored as data URLs in the result property.
    • Readasbinarystring (file): reads the files and saves a string in the result property.
    • Readasarraybuffer (file): reads the files and saves a arraybuffer containing the file's human capacity in the result property

Read the same local picture separately, and print out the information saved in the result property in contrast to the following:

Readastext (file,encoding):

Readasdataurl (file):

By comparing the above we find that these methods of reading files provide 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 before uploading the preview function.

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

The error event is triggered by the inability to read the file for a variety of reasons, and a property code (error code) is stored in an object in the FileReader error property when the error event is triggered.

Use FileReader to do upload Preview example:

Html:

<label class= "Item_label" > Upload photos:
 <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 (); Extract the last occurrence from the string. The character after, and convert lowercase var result = Uploadtype.indexof (Fileext);
 Finds whether the suffix name meets the criteria and returns a negative number if the >=0 is met;
 _alertmsg = $ (' #error_text ');
 var ofreader = new FileReader ();
 if (This.files.length = = 0) {return;} var ofile = this.files[0];
  
 If you have only one file, you only need to access the first element in the FileList object.
 if (ofile.size/1024 < MB) {_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 ();
 
 }; Ofreader.readasdataurl (ofile); Starts a read operation in the background.
  When all the contents of an image file are loaded, they are converted to a data:url and passed to the onload callback function ofreader.onload = function (ofrevent) {//When the read operation completes successfully. document.getElementById ("Uploadpreview"). src = Ofrevent.targEt.result;
};
 };

Effect and the returned picture URL:

The above is the entire content of this article, I hope to help you learn.

Related Article

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.