JS Mobile Multi-image upload preview to the backend

Source: Internet
Author: User

HTML5 defines FileReader as an important member of the file API for reading files, and the FileReader interface provides a way to read the file and an event model that contains the read result, according to the definition of the system.

The FileReader instance has 4 methods, 3 of which are used to read the file and the other to interrupt the read. The following table lists these methods, along with their parameters and capabilities, and it is important to note that the method does not return read results regardless of the success or failure of the read, which is stored in the result property.

Method Name Parameters Description
Abort None Interrupt Read
Readasbinarystring File To read a file as a binary code
Readasdataurl File Read the file as Dataurl
Readastext file, [encoding] To read a file as text

Readastext: The method has two parameters, where the second parameter is the encoding of the text, and the default value is UTF-8. This method is very easy to understand, the file is read in text mode, the result of reading is the content of this text file.
readasbinarystring: This method reads a file as a binary string, usually we pass it to the back end, and the backend can store the file through this string.
Readasdataurl: This is the method used in the example program, which reads a file as a string beginning with data: The essence of this string is that the data Url,data URL is a scheme to embed small files directly into the document. Small files here usually refer to files in the format of images and HTML.

The FileReader also contains a complete set of event models for capturing the state of the file when it is read, and the following table summarizes these events.

Events Description
Onabort Trigger on interrupt
OnError Triggered when an error occurs
OnLoad Trigger when file read completes successfully
Onloadend Read completion trigger, regardless of success or failure
Onloadstart Trigger at start of Read
OnProgress Read in

Once a file begins to read, the result property of the instance is populated, regardless of success or failure. If the read fails, the value of result is null, otherwise it is the result of the read, and the vast majority of programs will fetch the value when the file is successfully read.

After understanding the FileReader provided by H5, we use FileReader to enable colleagues to select multiple images and upload them.

First, in HTML to add a file form, and set it to multiple (browser in the multiple, disabled, checked, selected and other such properties to parse, as long as these properties exist, the default will be resolved to true, No matter what you set up is disabled=true or disabled=false also disabled="" , if you don't want these attributes to work, you can only use JS to remove these attributes unless you set them. ), and set accept="image/*" the file to select only the type of picture, with the following code:

<input type="file"  accept="image/*" name= " Upload " id="upload" multiple><input type="hidden " id="hiddenimgurl" />   <!--set this hidden field so that it is easy to store the image address returned after uploading to the server-- >
//image UploadvarFile ={upload:function (e) {varSelf = This; varFiles =E.target.files; varType = files[0].type.split ('/')[0]; if(Type! ='Image') {alertmsg ('please upload a picture'); return; }        //var size = Math.floor (file.size/1024/1024); //if (Size > 3) {//alert (' image size must not exceed 3M '); //return; //};         for(vari =0; i < files.length; i++) {            varReader =NewFileReader ();            Reader.readasdataurl (Files[i]); Reader.onloadstart=function () {//to add some events or effects before uploading, such as loading ... The animation effect            }; Reader.onloadend=function (e) {varDataurl = This. Result; varimaged =NewImage (); IMAGED.SRC=Dataurl; Imaged.onload= function () {//compress a picture with canvas                    varCanvas = document.createelement ('Canvas'); varCTX = Canvas.getcontext ('2d'); varW =0; varh =0; if( This. width > This. Height) {h= +; varScale = This. Width/ This. Height; H= h > This. Height? This. height:h; W= h *Scale ; }                    Else{W= +; varScale = This. Width/ This. Height; W= w > This. width? This. width:w h= w/Scale ; }                    varANW = Document.createattribute ("width"); varAnh = Document.createattribute ("Height"); if( This. width > This. Height) {Anw.value=h; Anh.value=W; }                    Else{Anw.value=W; Anh.value=h;                    } canvas.setattributenode (ANW);                    Canvas.setattributenode (Anh); if( This. width > This. Height) {ctx.translate (H,0); Ctx.rotate ( -* Math.PI/ the) Ctx.drawimage ( This,0,0, W, h);                    Ctx.restore (); }                    Else{ctx.drawimage ( This,0,0, W, h); } Dataurl= Canvas.todataurl ('Image/jpeg'); //callback function used to submit data to the databaseSelf.callback (Dataurl);            };        }; }    },    Event: Function () {$ ("#upload"). Change (function (e) {file.upload (e);    }); }, Callback:function (Dataurl) {$.ajaxsettings.Async=false;//It is necessary to change the Ajax asynchronous to synchronous to take the picture address returned and saved in the hidden field and pass it to the next page as a parameter in the Address bar, because the returned image address is not a JSON array, but a single JSON string. So you can only stitch the returned image address JSON string together as a parameter to the next page$.post (URL, dataurl, function (res) {//convert images from the Base64 picture stream to a normal picture path and upload to the server            varImgurl = $ ("#hiddenImgUrl"). Val (); if(res.success) {$ (". Loading"). Hide (); if(Imgurl! ="") {                    $("#hiddenImgUrl"). Val (Imgurl +"|"+ Res.imgurl);//Add a | To the next page to make it easier to convert the passed-in image address parameter to an array}Else {                    $("#hiddenImgUrl"). Val (Res.imgurl); }                varImgurl = $ ("#hiddenImgUrl"). Val (); Window.location.href="apply.html?imgurl="+Imgurl; } Else{alert (res.message); }        }, "JSON"); }, Init:function () { This.Event(); }}file.init ();

Because of the synchronous way of uploading to the server via post, I am always unable to implement the animation effect in the loading process, and put the animation effect in the reader.onloadstart method still does not work, finally can only put in the $("#upload").change(function (e) {}) method, the code is as follows:

Event : Function () {        $ ("#upload"). Change (function (e) {            $("  . Loading"). Show ();                      File.upload (e);        });    

The above is to upload more than one picture at the same time and the image into the next page to continue to follow up, then how to upload a number of pictures at the same time on this page to preview these pictures? In fact, the method is also very simple, the upper callback function inside the return value of the $.post contains the upload to the server after the image path, the path is assigned to the IMG tag src, and then inserted into the page is OK, the code is as follows:

callback:function (Dataurl) {$.post (URL, dataurl, function (res) {//convert images from the Base64 picture stream to a normal picture path and upload to the server            if(res.success) {$ (". Loading"). Hide (); varresult ='<div class= "result" >'+res.imgurl+'"/></div>'; vardiv = document.createelement ('Div'); Div.innerhtml=result;                           Document.body.appendChild (DIV); } Else{alert (res.message); }        }, "JSON"); }

The above when previewing the picture because does not need to jump, does not need to pass in the return all picture's path as the parameter, therefore also does not need to set the Ajax asynchronous to synchronize.

JS Mobile Multi-image upload preview to the backend

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.