Upload images using AJAX, support image instant browsing, support JS image compression to the server

Source: Internet
Author: User

Upload images using AJAX, support image instant browsing, support JS image compression to the server

Ajax uploads mainly use var reader = new FileReader () This method

JS image compression is mainly done using canvas

Source:

/** * js use form to upload images, support local preview of selected images, support to carry custom parameters * @param {string} params.previewimgid preview picture control ID, you can preview upload image * @param {string} Params.url Submit url* @param {function} params.success upload interface callback function * @param {Boolean} Params.para Ms Upload other parameters submitted several, the system will previewimgid URL success these three parameters filtered by the other parameters to the server use example:  & Lt;div onclick= "Shangchuan ()" > Upload </div> function Shangchuan () {jsuploadimage ({"Diyparam": "1111", "diyparam1        ":" 222 "," Previewimgid ":" Yulan "," url ":" User.php?act=photosave "," Success ": function (data) {Console.log (data); }})};*/function Jsuploadimage (params) {//Initialize data Params.previewimgid = Params.previewimgid | |    ""; Params.url = Params.url | |    ""; params.success = Params.success | |    ""; Create the File Upload control if (document.getElementById ("Imgfile") ==null) {var inputele=document.createelement ("input");//Create           Input inputele.id= "Imgfile";         inputele.type= "File"; Inputele.accept= "Image/png,image/jpeg,image/jpeg,dcim/*;capture=camera";          Inputele.style= "Display:none;";         Inputele.onchange = function () {Showphoto ()};         Inputele.multiple = false;              Document.body.appendChild (Inputele);     } var imgfile = document.getElementById ("Imgfile");              Imgfile.click ();                Preview picture after selected file function Showphoto () {//file object var = document.getElementById ("Imgfile"). Files[0];        Read the suffix to determine if the allowable file var filesuffix = file.name.substring (file.name.length-4); var allowfile = ". Jpg|. Png|.        GIF ";            if (Allowfile.indexof (Filesuffix.tolowercase ()) ==-1) {alert ("Please use" +allowfile+ "suffix file");        return false;        }//If the ID of the display control is passed, display local preview var reader = new FileReader () reader.readasdataurl (file);                        Reader.onload = function (e) {var imgbase64data = E.target.result;           Show previewif (""! = Params.previewimgid) document.getElementById (params.previewimgid). src = imgbase64data; If you do not compress the direct upload//savephoto (imgbase64data)//To shrink the picture, then upload the Compressphoto (imgbase 64data,1000,1000,function (Imgbase64databack) {//Submit service Save Data sav                      Ephoto (Imgbase64databack)});                 }}//Submit data Function Savephoto (base64data) {var formData = new FormData (); Add additional parameters for (Var key in params) {if (key!= "Previewimgid" && key!= "url" && key!= "succes          S ") {Formdata.append (key, Params[key]);        }}//Add file parameters using Base64 formdata.append ("Imgfile", encodeURIComponent (Base64data));                Add file parameter to upload, but this test does not support the image compression, so the phone does not use this way//formdata.append (' imgfile ', file); Ajax upload $.ajax ({Url:paraMs.url, type: ' POST ', Cache:false, DataType: "JSON", Data:formdata,                Processdata:false, Contenttype:false}). Done (function (res) {if (params.success!= "") {            Params.success (RES);        }). Fail (function (res) {alert ("Upload failed");    }); }}/** * JS uses canvas to compress images * @param {string} imgbase64data image Base64 data * @param {string} maxWidth maximum Height * @param {function} maxheight maximum width * @param {Boolean} fun callback function, the parameter is the processed image data use example: Compressphoto (i Mgbase64data,maxwidth,maxheight,function (Imgbase64data) {//Return image Data processing}) */function Compressphoto (ImgBase64Data,    Maxwidth,maxheight,fun) {var img = new Image ();    The canvas var canvas = document.createelement (' canvas ') required to scale the picture;    var context = Canvas.getcontext (' 2d ');        Base64 address picture after loading img.onload = function () {//Picture original size var originwidth = this.width; Var Originheight = This.height;        Target size var targetwidth = originwidth, targetheight = originheight; Picture size exceeds 400x400 limit if (Originwidth > MaxWidth | | originheight > MaxHeight) {if (originwidth/or                Iginheight > Maxwidth/maxheight) {//wider, size-limited by width targetwidth = maxWidth;            Targetheight = Math.Round (MaxWidth * (originheight/originwidth));                } else {targetheight = MaxHeight;            Targetwidth = Math.Round (MaxHeight * (originwidth/originheight));        }}//canvas to zoom the picture canvas.width = Targetwidth;        Canvas.height = Targetheight;        Clear Canvas context.clearrect (0, 0, targetwidth, targetheight);        Picture compression Context.drawimage (img, 0, 0, targetwidth, targetheight);    var base=canvas.todataurl ("Image/jpeg", 0.7),//canvas transcoding to Base64 fun (base);//return processing}; IMG.SRC = Imgbase64datA;} 

Examples of Use:

<div onclick= "Shangchuan ()" > Upload </div><script type= "Text/javascript" > function Shangchuan () {        jsuploadimage ({"Diyparam": "1111", "diyparam1": "222", "Previewimgid": "Yulan", "url": " User.php?act=photosave "," Success ": function (data) {            console.log (data);}}        )   }; </script>

Source: jsfun.cn
http://www.jsfun.cn/#codecollect

Upload images using AJAX, support image instant browsing, support JS image compression to the server

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.