当前位置: 动力学知识库 > 问答 > 编程问答 >

Preview image uploaded in jquery

问题描述:

I have next code in html and css, and i want using jquery for show image uploaded in preview classes.

How to do this?

Also, how can I delete images uploaded?

jsFiddle Demo

html

<form id="myform">

<div class="preview">

<span class="btn_upload">

<input type="file" multiple id="imag" title="" />

Add

</span>

</div>

<div class="preview">

<span class="btn_upload">

<input type="file" multiple id="imag" title="" />

Add

</span>

</div>

</form>

css

.btn_upload {

cursor:pointer;

display:inline-block;

overflow:hidden;

position:relative;

margin-top:10px;

color:#fff;

text-shadow:0 -1px 1px rgba(0,0,0,0.25);

-moz-box-shadow:inset 0 1px 0 0 #abbeef;

-webkit-box-shadow:inset 0 1px 0 0 #abbeef;

box-shadow:inset 0 1px 0 0 #abbeef;

background:0;

filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#2a72d4',endColorstr='#1160b8');

background-color:#2a72d4;

border:1px solid #166b8a;

padding:5px 10px;

}

.btn_upload input {

cursor:pointer;

height:100%;

position:absolute;

filter:alpha(opacity=1);

-moz-opacity:0.01;

opacity:0.01;

}

.preview {

width:120px;

height:100px;

border:1px solid red;

margin-right:10px;

float:left;

}

Thx for answer.

网友答案:

I recommend you to not have several controls with the same ID. Use an img control to render the image, and that img control will use the preview class.

This is how I usually do it:

Markup:

<form id="myform">
   <div class="preview">
      <span class="btn_upload">
      <input type="file" multiple id="imag" title="" />
      Add
      </span>
<img id="ImgPreview" src="#" class="preview" />

   </div>
   <div class="preview">
      <span class="btn_upload">
      <input type="file" multiple id="imag2" title="" />
      Add
      </span>
   </div>
</form>

Jquery code:

$("#imag").change(function () {
            // add your logic to decide which image control you'll use
            var imgControlName = "#ImgPreview";
            readURL(this, imgControlName);
        });

  function readURL(input, imgControlName) {

            if (input.files && input.files[0]) {
                var reader = new FileReader();

                reader.onload = function (e) {
                    $(imgControlName).attr('src', e.target.result);
                }

                reader.readAsDataURL(input.files[0]);
            }
        }

Here is your fiddle modified: http://jsfiddle.net/J24yN/2/

Note that I only did it for the first uploader, but you can easily extend the code to several uploaders.

EDIT:

I updated my answer to add the remove image logic. Again, you have to add your own logic in order to select the actual image you want to remove in case you have different controls:

http://jsfiddle.net/J24yN/4/

分享给朋友:
您可能感兴趣的文章:
随机阅读: