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
- 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
- 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
- Separate picture upload UI, support for picture previews (ie6+, other browsers) and zooming (ie10+, other browsers)
- The upload core is separated from the UI interface and can be easily customized with the upload interface including the upload button
- Upload files can also specify the upload parameters, support upload type filtering
- Complete event callbacks that can be processed separately for each upload process
- 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