JQuery implementation input upload image display thumbnail

Keywords: html5 Mobile JQuery Javascript



Recently, I made a set of mobile shopping mall page, which has the function of uploading pictures to display thumbnails on the refund application page. I haven't done this before, so I sorted it out.

First HTML:

<p>Upload picture:</p>
  <div id="imgPreview"></div>
  <span class="upload-img"><input id="fileUpload" accept="image/*" type="file" multiple="multiple"></span>
  </div>

CSS :

#imgPreview {
  float: left;
  border: none;
}
#imgPreview img {
  margin-right: 10px;
  width: 50px;
  height: 50px;
}
upload-img {
  display: block;
  float: left;
  width: 50px;
  height: 50px;
  overflow: hidden;
  position: relative;
  background: url("../images/self/upload.png") no-repeat 0;
  background-size: contain;
}
//This is to change the upload button style and set input to transparent color
.upload-img input {
  height: 50px;
  opacity: 0;
  filter: alpha(opacity=0);
  position: absolute;
  top: 0;
  right: 0;
}

Here I change the input of the upload button into a transparent color, and then use a span cover with a + background image to change the style of the upload button. If you don't use the image, you can set the span style to achieve the desired effect.

JQuery :

<script type="text/javascript">
$(function () {
$("#fileupload").change(function () {
if (typeof (FileReader) != "undefined") {
var dvPreview = $("#imgPreview");
dvPreview.html("");
var regex = /(.jpg|.jpeg|.gif|.png|.bmp)$/;
$($(this)[0].files).each(function () {
    var file = $(this);
    if (regex.test(file[0].name.toLowerCase())) {
        var reader = new FileReader();
        reader.onload = function (e) {
            var img = $("<img />");
            img.attr("src", e.target.result);
            dvPreview.append(img);
        }
        reader.readAsDataURL(file[0]);
    } else {
        alert(file[0].name + " is not a valid image file.");
        dvPreview.html("");
        return false;
    }
});
} else {
alert("This browser does not support HTML5 FileReader.");
}
});
});

</script>

Bound an input change() Event. When the event is triggered, it will first check whether the browser supports HTML5 FileReader API, if supported, will execute a each Cycle.
In each cycle, use regular expressions to determine whether the file suffix is in the image format. If it is in the image format, if it is in the image format, use readAsDataURL Method to read its BASE64 encoding, then take it as the src attribute value of the img element, add the img element to the imgPreview to upload the display thumbnail.



By Eric hedgedog
Link: http://www.jianshu.com/p/8eaa56a37064

Posted by Dragoonus on Sat, 04 Apr 2020 16:58:33 -0700