Project review 1-image upload-form form or base64-front-end picture compression

Source: Internet
Author: User

The first project finally on the line, is called pro-green raise the public welfare crowdfunding platform, end, the computer side also has the background interface most are I completed, a few months come over, feel a lot of harvest, feel to summarize.

The first thing to think about is the picture upload problem. It is foolish to use form forms to upload images in situations where the form data is usually Ajax-uploaded. Then also did not think of using jquery form plugin.

Backstage colleagues to the scheme is to use an iframe to write a form form, and then upload the image after the automatic submission of the form, he will picture the address on the server to jump page part of the URL, I'll intercept the way.

Scenario One: Iframe+form form

    <formAction= "/user/uploadidcard.do"class= "Fileform picupload"enctype= "Multipart/form-data"Method= "POST">        <inputtype= "File"ID= "Uploadpic"name= "File">        <label for= "Uploadpic"ID= "Filebtn">            +            <imgsrc="" />        </label>        <inputtype= "text"name= "Turnurl"class= "Turnurl">    </form>

    $ (". Turnurl"). Val (window.location.pathname);    $ (function(event) {        event.preventdefault ();        $ ("form"). Submit ();    });

In the interface that requires uploading images, the IFRAME is introduced into the common library, the URL of the image is obtained and the image is displayed in the IFRAME.

//extracting paths in an IFRAMEfunctioniframe (EL) {varBaseURL = ""; varcode, FilePath; varPlace = $ (EL) [0].contentwindow.location.search;    Console.log (place); if(place) {code= Place.match (/code=\d+/) [0].substr (5); if(Place.match (/filepath=\s+/) ) {FilePath= Place.match (/filepath=\s+/) [0].substr (9); } $ (EL). Contents (). Find (". Tip"). CSS (' color ', ' #d0021b '));        Console.log (FilePath); Switch(code) { Case"200": $ (EL). Contents (). Find (". Tip"). Text (' Upload successful '); $ (EL). Contents (). Find (". Tip"). CSS (' color ', ' #55a012 ')); $ (EL). Contents (). Find ("#fileBtn >img"). Show (). attr ("src", BaseURL + "/" +FilePath); return"/" +FilePath;  Case"206": $ (EL). Contents (). Find (". Tip"). Text (' File too large ');  Break;  Case"207": $ (EL). Contents (). Find (". Tip"). Text (' File type error '));  Break;  Case"208": $ (EL). Contents (). Find (". Tip"). Text (' System error '); }    }}

Scenario Two: Later found that this approach has two problems, one is the user sent the picture is too large, the background did not do compression (backstage colleagues are too busy, in order to accommodate them, on our front-end do compression). The second is, after uploading the image successfully, the picture is displayed on the IFRAME, which requires a certain response time, the user sometimes reflects the image can not be transmitted, in fact, only the background has not returned ...

and decided to use Base64 to upload it to the backstage.

    <inputtype= "File"ID= "Uploadpic"name= "File">    <label for= "Uploadpic"ID= "Filebtn">        +        <imgclass= "Showpic"src="" />    </label>    <spanclass= "Tip">Please upload the image, size within 2M<BR/>(Image type can be jpg,jepg,png,gif,bmp)<BR/>Recommended picture ratio is 640*400</span>    <inputtype= "text"name= "Turnurl"class= "Turnurl">    <CanvasID= "Uploadimg"style= "Display:none"></Canvas>

The structure is similar to the original, just one more canvas

$ ("#uploadPic"). On (' Change ',function(event) {Event.preventdefault (); Console.log ($ ( This) [0].files); varFile = $ ( This) [0].files[0]; if(file.size>2097152) {alert ("Upload image please less than 2M"); return false; }        if(!/image\/\w+/. Test (File.type)) {Alert ("The file must be a picture!" "); return false; }        varReader =NewFileReader ();        Reader.readasdataurl (file); Reader.onload=function(e) {Createcanvas ( This. Result); }    }); functionCreatecanvas (src) {varCanvas = document.getElementById ("uploadimg"); varCXT = Canvas.getcontext (' 2d '); Canvas.width= 640; Canvas.height= 400; varIMG =NewImage (); IMG.SRC=src; Img.onload=function() {            //var w=img.width;            //var h=img.height;            //canvas.width= W;            //canvas.height=h;Cxt.drawimage (IMG, 0, 0,640,400); //cxt.drawimage (img, 0, 0);$ (". Showpic"). Show (). attr (' src ', canvas.todataurl ("Image/jpeg", 0.9)); $.ajax ({URL:"/front/uploadbybase64.do", type:"POST", data: {"Imgstr": Canvas.todataurl ("Image/jpeg", 0.9). Split (', ') [1]}, Success:function(data) {Console.log (data); $(". Showpic"). Show (). attr (' Data-url ', "/" +Data.url);        }            }); }    }

1. The first is to use the input file information, determine the file size file.size, and whether the file is a picture File.type

2. Obtain the Base64 data of this image via the HTML5 FileReader interface.

3. Pass this base64 into the canvas as a src of a graph, this time can set the resolution size of the picture, ensure that the uploaded image is a unified resolution. Of course, you can also follow the original size of the picture.

4. Before Ajax, the processed base64 is displayed directly (so that users can immediately see their uploaded images), and then Canvas.todataurl ("Image/jpeg", 0.9). Split (', ') [1] (Type image/ JPEG, you can use the second parameter to set the quality of the image) to the background of the corresponding interface

5. The URL returned in the background is tied to the Data-url property of the picture, and it is good to get this data-url when Ajax turns over the entire form, so that the user can see the fastest time, and the URL is actually in the process of Ajax to the background.

PostScript: These two programs have a problem, will upload a lot of redundant images in the background. But backstage colleagues seem to have no opinion, embarrassing.

The actual effect is this http://www.qqchou.org/qqcweb/pages/photoIframe.html

Project review 1-image upload-form form or base64-front-end picture compression

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.