Image upload preview Feature implementation

Source: Internet
Author: User

The picture preview function is very common in the website development, the previous picture preview is a very simple function, only need JS obtains the upload the path, then sets the path to the one IMG tag src to be possible, but now many browsers appear the security aspect consideration, does not allow directly obtains the file path, The path obtained through the value of file is Fakepath, so it becomes difficult to get the path, but after H5, the file preview can be realized by JS FileReader: The code is as follows:

JS Processing code:

<script type= "Text/javascript" >document.getElementById (' File1 '). onchange=function(evt) {//If the browser does not support FileReader, it does not process    if(!window. FileReader) {return; }    varFiles =Evt.target.files;  for(vari = 0, F; f = files[i]; i++) {                  if(!f.type.match (' image.* ')) {                Continue; }          varReader =NewFileReader (); Reader.onload= (function(thefile) {return function(e) {//img Elementdocument.getElementById (' Img1 '). src =E.target.result;            };              }) (f);        Reader.readasdataurl (f); }  }</script>

HTML tags are simple: You need a file tag and an IMG tag

   <id= "IMG1"  width= "  height=" " Style= "padding-top:10px"/>    <type= " File "  name=" file "  ID=" file1 "/>

This enables the preview function of the file.

Image upload preview Feature implementation

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.