Simulate type=file; upload and preview a picture

Source: Internet
Author: User

Recent Project Member Center, to do an upload local img and preview the effect. The effect is probably this way. I have not done it before, Stones finally finished feeling it is necessary to tidy up, write a blog to play.

650) this.width=650; "src=" "style=" float: none; "title=" Boke2.png "alt=" Wkiol1x1jafqqfowaacxfbyq7be758.jpg "/>

650) this.width=650; "src=" Http:// "title=" Boke4.png "alt=" Wkiol1x1kvibwdvxaaibvu27cnk234.jpg "/>

650) this.width=650; "src=" "style=" float: none; "title=" Boke3.png "alt=" Wkiom1x1i3aczqizaafugcub6ss565.jpg "/>

The overall effect might look like this:

1. Click anywhere in the box; pop-up Select File window;

2. After the selection, the box area preview;

3. Click the box again to change the picture.

Let's talk about the whole realization process.

The structure of the HTML code is probably the case.

<div class= "Imgitem secondimg" > <div class= "U-add-img-icon u-fileuploadcontainer" > </div> <input id= "FileImage2" type= "file" multiple= "class=" U-fileinput "> <span class=" Imgcontainer "></span> <span class= "backimg" >*** reverse </span> </div>


1. preferred is to simulate the type=file; Click to select the effect of the file.

The outermost imgitem Set the fixed width high,postion:realative;

Then add an icon to upload the image, and tell the user to upload the preview image.

Finally,input type= the "file" position Absolutely, set the transparency to 0, andthe position just fills the outer bounds of the box. You can click anywhere in the box to pop the window and select the file's box.

The Css code is as follows:

.imgitem {  width: 240px;  height:  160px;  display: inline-block;  border: 1px  #d5d4d4  dotted;   text-align: center;  line-height: 160px;  position: relative;//relative positioning   } .u-fileInput{  width: 240px;  height: 160px;   overflow: hidden;  position: absolute;  right: 0;  top: 0;   opacity: 0;//Transparency for 0  filter: alpha (opacity=0); /transparency is 0, compatible with ie8  cursor: pointer;  }  //add-img icon   .u-add-img-icon  {  width: 74px;  height: 61px;  background: url (.. /images/member/add-img-icon.png)  no-repeat;  display: inline-block;   Vertical-align: middle; 

2. Select post-preview; This place is quite ingenious, because we know type=file; When you select a file, you select to return a document object; Createobjecturl can accept a file object, returns the URLof the file,and then specifies the img SRC around the url, you can implement the preview image.

This place is slightly more complex;

The preferred package is a small plugin for uploading previews: called Uploadpreview

About Createobjecturl, do not know Baidu, look. Not the focus of this article;

/** Name: Image upload Local preview * Author: Jia Jinjun * Date: September 11, 2015 * Introduction: Based on jquery extension, image upload Preview plugin * parameter description:  imgobj: Image jquery object; Type: Supported file type; callback: Select the file to display the image after the callback method; * How to use:  <div></div><input type= "file"  id = "Up"  /> the IMG tag that needs to be previewed outside   sets a div  then gives the upload control ID to the Uploadpreview event $ ("#up"). Uploadpreview ({ imgobj :  $ ("#temp"),  type: ["GIF",  "JPEG",  "JPG",  "BMP",  "PNG"], callback:  function  ()  { }); */jquery.fn.extend ({    uploadpreview:  function  (opts)  {        var _self = this,             _this = $ (This);         opts = jquery.extend ({             imgObj: null,             type: ["GIf ", " JPEG ", " JPG ", " BMP ", " PNG "],             callback: function  ()  {}        },  opts | |  {});        _self.getobjecturl = function  (file)  {            var url = null;             if  (window.createobjecturl ! = undefined)  {                 url = window.createobjecturl (file)              } else if  (window. url != undefined)  {                 url = window. Url.createobjectuRL (file)             } else if  ( window.webkiturl != undefined)  {                 url = window.webkiturl.createobjecturl (file)              }             return url        };         _this.change (function  ()  {             if  (This.value)  {                 if (!opts.imgobj) {                     return;                 }                 if  (! REGEXP ("\. ("  + opts.type.join ("|")  +  ") $",  "I"). Test (This.value.toLowerCase ()))  {                     alert ("File format error, must be"  +  Opts.type.join (",")  +  "one of");                     this.value =  "";                     return false                 }                 if  ( Document.selection)  {                    try {                         opts.imgobj.attr (' src ',  _self.getobjecturl (this.files[0))                      } catch  (e)  {                         var src =  "";                          var obj = opts.imgobj;                         var div = obj.parent (" Div ") [0];                ();                         if  (top != self)  {                              window.parent.document.body.focus ()                           } else {                             _self.blur ()                         &nBSP;}                          src = document.selection.createrange () .text;                          document.selection.empty ();                         obj.hide ();                          obj.parent ("div"). CSS ({                              ' Filter ':  ' Progid:DXImageTransform.Microsoft.AlphaImageLoader (sizingmethod=scale) '                          });                          div.filters.item ("DXImageTransform.Microsoft.AlphaImageLoader") .src = src;                      }                }  else {                     opts.imgobj.attr (' src ',  _self.getobjecturl (this.files[0))                  }                 opts.callback ()              }        })     }); 

Then there is the element invocation of input type =file:

The picture adds a preview effect of $ (". U-fileinput"). each (function () {var $this = $ (this);        $this. Uploadpreview ({imgobj: $this. Next (). FIND ("img"), callback:uploadhandler});            Get URL settings img src succeeded, callback, hide add-icon; display picture function Uploadhandler () {$this. Next (). Show ();        $this. Prev (). hide (); }    });

3. Finally click the box to change the picture is relatively simple, here is not much to put it.

Make a little progress every day.

This article is from the "Shuizhongyue" blog, make sure to keep this source

Simulate type=file; upload and preview a picture

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: 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.