HTML5 image upload, support image Preview, compression, and progress display, compatible with ie6+ and standard browser

Source: Internet
Author: User
Tags base64

Original: HTML5 image upload, support image Preview, compression, and progress display, compatible with ie6+ and standard browser

Previously written upload components, see build HTML5 File Upload components, to achieve progress display and drag upload, compatible with ie6+ and other standard browser, to deal with the general upload no problem, but if it is uploading pictures, and need to preview, the force has not caught, take advantage of leisure time, Added a separate picture upload UI for the upload component, support for picture previews and zooming (by resizing the image to compress the image).

Upload Component Features
    1. Lightweight, not dependent on any JS library, the core code (q.uploader.js) only about 700 lines, min version added up to less than 12KB
    2. Pure JS Code, no flash, no need to change the background code to achieve with the progress bar (ie10+, other standard browser) upload, other (eg:ie6+) automatically downgrade to the traditional way to upload
    3. Separate picture upload UI, support for picture previews (ie6+, other browsers) and zooming (ie10+, other browsers)
    4. The upload core is separated from the UI interface and can be easily customized with the upload interface including the upload button
    5. Upload files can also specify the upload parameters, support upload type filtering
    6. Complete event callbacks that can be processed separately for each upload process
    7. Convenient UI interface, the upload interface can be customized freely

Effects such as. Because the browser is different, the compression effect is different, a 1.1MB, the resolution of the image of 1920x1200, the resolution is scaled to 1024x640, IE11 after uploading for 199kb,chrome45 after uploading for 277kb,firefox41 after uploading for 360KB.

Using code

HTML code, import style and JS upload component, define the upload button and view:

<Linkhref=".. /css/uploader-image.css "rel= "stylesheet"type= "Text/css" /><Div>    <aID= "Upload-target"class= "X-button">Add pictures and upload</a></Div><DivID= "Upload-view"></Div><Scripttype= "Text/javascript"src=".. /q.uploader.image.all.js "></Script>

JS Component invocation:

varuploader =Newq.uploader ({URL:"Api/upload.ashx", Target:document.getElementById ("Upload-target"), View:document.getElementById ("Upload-view"),    //Auto:false,    //Picture ZoomScale : {//picture format to zoom inTypes: ". jpg",        //Maximum picture size (width|height)maxwidth:1024    }});//Uploader.start ();

There is generally no need to change the background code, but if you use the image zoom (compression), Firefox, Chrome earlier version upload, the background may not get the file name, need to be processed slightly. Take the example of asp:

HttpRequest request =context. Request;intc =request. Files.count;//receive uploaded data and save to server for(inti =0; I < C; i++) {Httppostedfile file=request.        Files[i]; //to be compatible with some older browsers, the file name passed by the upload component is preferred here    stringFileName = request["FileName"]; if(string. IsNullOrEmpty (filename)) FileName =System.IO.Path.GetFileName (file.    FileName); stringPath = context. Server.MapPath ("~/upload/"+fileName); File. SaveAs (path);

About uploading

See Creating HTML5 File Upload components for progress display and drag-and-drop uploads, compatible with ie6+ and other standard browsers

About previewing

ie10+ and other browsers use the HTML5 API, and other browsers use filter previews. It should be noted that ie8+ due to security considerations, will not get the real address of the file, need special treatment.

//Generate picture Preview address (HTML5)functionreadasurl (file, callback) {varURL = window. URL | |Window.webkiturl; if(URL)returnCallback (Url.createobjecturl (file)); if(window. FileReader) {varFR =NewFileReader (); Fr.onload = function(e) {callback (E.target.result);        };    Fr.readasdataurl (file); } Else if(File.readasdataurl) {callback (File.readasdataurl ()); }}//Picture Previewfunctionpreviewimage (box, task, callback) {varinput =task.input, File= Task.file | | (Input.files? input.files[0]: undefined); if(file) {//ie10+, Webkit, Firefox etcReadasurl (file,function(SRC) {if(src) box.innerhtml = '  '; Callback&&callback (SRC);    }); } Else if(input) {varsrc =Input.value; if(!src | |/^\w:\\fakepath/. Test (SRC))            {Input.select (); //solve the problem of IE denied accessParent.document.body.focus (); //get picture Real address            if(document.selection) src =Document.selection.createRange (). text; }        if(SRC) {box.innerhtml= '  '; Try {                if(Browser_ie > 6) box.style.filter = "Progid:DXImageTransform.Microsoft.AlphaImageLoader (sizingmethod= ' scale ', SRC = ' "+ src +" ') "; } Catch(e) {}} callback&&callback (SRC); }}
About scaling (compression)

The idea is to resize the image by canvas, generate base64 data, and then convert to binary object uploads via the HTML5 API (BLOB).

//Convert Dataurl to blob object for Ajax uploadsfunctionDataurltoblob (base64, mimetype) {vards = Base64.split (', '), Data= Atob (ds[1]), arr= [];  for(vari = 0, len = data.length; i < Len; i++) {Arr[i]=data.charcodeat (i); }    if(BLOB)return NewBlob ([NewUint8array (arr)], {type:mimetype}); varBuilder =NewBlobbuilder ();    Builder.append (arr); returnBuilder.getblob (mimetype);}//Picture Zoomfunctionscaleimage (SRC, mimetype, OPS, callback) {varImage =NewImage (); IMAGE.SRC=src; Image.onload=function () {        varwidth =image.width, Height=Image.height, MaxWidth=Ops.maxwidth, MaxHeight=Ops.maxheight, Haswidthscale= MaxWidth && width >MaxWidth, Hasheightscale= maxheight && Height >MaxHeight, Hasscale= Haswidthscale | |Hasheightscale; //No compression required        if(!hasscale)returnCallback && Callback (false); //Scale by width        if(haswidthscale) {width=MaxWidth; Height= Math.floor (Image.height * Width/image.width); }        //based on height scaling        if(hasheightscale) {height=MaxHeight; Width= Math.floor (image.width * Height/image.height); }        varCanvas = document.createelement ("Canvas"), CTX= Canvas.getcontext ("2d"); Canvas.width=width; Canvas.height=height; Ctx.drawimage (Image,0, 0, width, height); Callback&&Callback (Canvas.todataurl (mimetype), mimetype); };}

See also the source code and sample codes.

Code download

ASP. NET or other background sample code

SOURCE Update please follow GitHub

Written in the last

If this article or the project is helpful to you, please do not hesitate to praise. Welcome to the Exchange!

HTML5 image upload, support image Preview, compression, and progress display, compatible with ie6+ and standard browser

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.