Preface
Today we talk about image uploading, single or multiple. Nowadays, there are countless major image uploading plug-ins, such as: Jquery's verupload.js, jQuery File Upload, Uploadify, jQuery.filter and so on. But. We won’t talk about the plug-ins mentioned above today. Let’s take a look at how to use FileReader in HTML5 to realize single and multiple image preview, delete, upload and other functions. Let’s take a look at the effect after implementation:
2|0 implementation 2|1 front-end partThis is the button that the user clicks. Our most important sentence is input type=file and a multiple attribute is given, which can meet the needs of uploading multiple pictures.
<div class=form-group form-row> <label class=col-sm-2 control-label uText>Club Album</label><div class=row> <div class=col-xs-10 col-sm- 8 mTop5> <label <input type=file accept=image/* name=ClubImagesUpload id=ClubImagesUpload class=hide multiple=multiple> <img src=/Images/registerNewSite/btn_addimg.png class=addImg/> </label> </div> </div></div>
The area below is used for image preview
<div class=form-group form-row id=preViewMore><div class=row> <div class=col-xs-9> <div id=clubInputImagePreview class=col-sm-9 img-preview img-preview-sm ></div> </div> </div></div>2|2 Style Section
What? You even have to look at the style to see if it’s still humane (wry smile)
2|3Js partFirst, let's analyze the html above. We use a label to wrap the input and an img tag. We hope that by clicking on the + picture in the rendering, a dialog box for selecting photos will pop up. Therefore, we need to give the label a label first. Click event:
$(#btnClubImg).click(function() { //TODO Something});Let's look at it next, because we want to get the uploaded file, and our file is mainly on the input, so we first get the input tag:
$(#btnClubImg).click(function() { var $input = $(#ClubImagesUpload); console.log($input);//Print the current element});Let’s print out the current input element label to see what it is.
When we expand the first item, we will find that the length in files is 0.
Okay, let's continue the analysis, because we want to be able to get the currently selected file when the input box changes. To put it simply, when a file is selected, we can get the currently selected file. This is the same as getting the text input in the input box. Therefore, after analysis, we know that we need to add a change event to the input tag:
$(#btnClubImg).click(function() { var $input = $(#ClubImagesUpload); console.log($input); $input.on(change, function () { console.log(this);// Print the changed current element});});Let's take a look and get what's inside the changed input element:
It can be clearly seen here that we have obtained the selected picture, including the last modification event, picture name, size and picture type (with the file type, we can judge whether the current user selects a picture, right? (squinting smile) )) Again, this is for a single file. If it is multiple files, there will be multiple files.
Looking down, we can see from the printout that we have got the file information we want on the files element of the input tag, we just need to get them:
var files = this.files; var length = files.length;
In this way, we can get all the files and the number of files. Then here comes the question. If we select multiple files, what if we output them one by one and display them on the page? When you saw the four words marked above, did two words flash in your mind? cycle
$.each(files, function (key, value) { //TOTO Something });By looping through the files obtained above, we can obtain the information of each file in turn. In this way, you can not only output them one after another, but if you want, you can also send them to heaven ~
var fileReader = new FileReader();//Instantiate a FileReader object var file_ = files[key];//Get the current file if (/^image///w+$/.test(file_.type)) {// Perform regular matching on the current file to see if it is the selected image fileReader.onload = function() {//Called when the reading operation is completed} }It is necessary to extend the knowledge points of FileReader:
FileReader is mainly used to read file contents into memory. Through a series of asynchronous interfaces, local files can be accessed in the main thread.
Using FileReader objects, web applications can asynchronously read the contents of files (or raw data buffers) stored on the user's computer. You can use File objects or Blob objects to specify the files or data to be processed.
Back to the topic, we have been able to get the file and get the return, so at this time, we only need to display the returned result.
$(#clubInputImagePreview).css(background-image, url( + this.result + ));
Let's print out this.result to see what it is:
It goes without saying that the image is converted into Base64 data format. Finally, we call readAsDataURL to read the file content and represent it as a data:url string.
fileReader.readAsDataURL(value);
In this way, you can get a simple image upload demo, but it is not final because you still need to add a lot of business. For example: after getting a preview image, the current label will be occupied. If you loop in next time and use the original label directly, the previous image will definitely be replaced. Then this is definitely not the effect we want. We hope to be able to display it in sequence. , rather than replacing the display. So, we still need to do some processing:
$(#clubInputImagePreview).css(background-image, url( + this.result + ));//Use apend to append a child node under the current element $(#clubInputImagePreview) .append(<img src='/Images/ registerNewSite/btn_r_del.png' class='clubsImage' id='ImgRemove' />);//Use after to append a sibling node to the current sibling node $(#clubInputImagePreview).after( <div id='clubInputImagePreview1' class='col-sm-9 img-preview img- preview-sm delImg' ></div>);
Then when we add the deleted image, we also need to give it a click event to make our current preview area disappear:
$(#ImgRemove).click(function () { $(this).parent().remove();});In the end, you will find that the result is not what we want. That is because the current ID is still there, so the next step cannot be performed. We only need to remove the ID of the current element, and then add an element with the same ID, so The browser will think this is a new element:
$input.removeAttr(id); var newInput ='<input type=file accept=image/* name=ClubImagesUpload id=ClubImagesUpload class=hide multiple=multiple>'; $(this).append($(newInput));
The final complete JS code is as follows:
var intP = 0; $(#btnClubImg).click(function() { var $input = $(#ClubImagesUpload);// console.log($input); $input.on(change, function () {// console.log(this); var files = this.files; var length = files.length; if (intP > 8) { layer.msg('No more pictures~', {}); return; } $.each(files, function (key, value) { var fileReader = new FileReader(); var file_ = files[key]; if (/^image///w+$/.test( file_.type)) { fileReader.onload = function() { if (intP > 8) { layer.msg('No more pictures~', {}); return; } if (key == 0 && intP == 0) { console.log(this.result); $(#clubInputImagePreview).css(background-image, url( + this.result + )); $(#clubInputImagePreview) .append( <img src=' /Images/registerNewSite/btn_r_del.png' class='clubsImage' id='ImgRemove' />); $(#clubInputImagePreview).after( <div id='clubInputImagePreview1' class='col-sm-9 img-preview img-preview-sm delImg'></div>); } else { $(#clubInputImagePreview + parseInt(intP) + ).css(background-image, url( + this.result + )); $(#clubInputImagePreview + parseInt(intP) + ).append( <img src='/Images/registerNewSite/btn_r_del.png' class='clubsImage' id='ImgRemove + parseInt(parseInt( 1) + parseInt(intP)) +' />); $(#clubInputImagePreview + parseInt(intP) + ).after( <div id='clubInputImagePreview + parseInt(parseInt(1) + parseInt(intP)) + 'class='col-sm-9 img-preview img-preview- sm delImg' ></div>); } if (key == 0 && intP == 0) { $(#ImgRemove).click(function () { $(this).parent().remove(); }); } else { $(#ImgRemove + parseInt(parseInt(1) + parseInt(intP)) + ) .click(function () { $(this).parent().remove(); }); } intP += parseInt(1); }; fileReader.readAsDataURL(value); } else { layer.msg(Format error<br/>Please select an image file); } }); }); $input.removeAttr(id); var newInput = '<input type= file accept=image/* name=ClubImagesUpload id=ClubImagesUpload class=hide multiple=multiple>'; $(this).append($(newInput)); }); SummarizeThe above is the Html5 implementation of single and multiple image upload functions introduced by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time!