Project practice a picture upload form or base64 front-end image compression (front image compression) _javascript tips

Source: Internet
Author: User
Tags base64

The first project is finally online, is a pro-green raised the public good platform, micro-letter, computer end and most of the background interface is my complete, a few months over, feel a lot of harvest, feel like to sum up.

The first thought is the problem of uploading pictures. It's silly to use form forms to upload images, usually when the form data is Ajax-uploaded. Then there was no thought of using the jquery form plugin.

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

Programme one: Iframe+form form

<form action= "/user/uploadidcard.do" class= "Fileform picupload" enctype= "Multipart/form-data" method= "POST" >
<input type= "file" id= "Uploadpic" name= "file" >
<label for= "Uploadpic" id= "filebtn" >
+

</label>
<input type= "text" name= "Turnurl" class= "Turnurl" >
</form > 
$ (". Turnurl"). Val (window.location.pathname);
$ ("#uploadPic"). On (' Change ', function (event) {
event.preventdefault ();
$ ("form"). Submit ();

In the need to upload the image of the interface into the IFRAME, in the call Common library of the IFrame method, get the image URL and display the picture in the IFRAME

Extracts the path
function iframe (EL) {
var baseurl = "";
var code, FilePath;
var place = $ (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
"a":
$ (EL). Contents (). Find (". Tip"). Text (' upload success ');
$ (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 "a":
$ (EL). Contents (). Find (". Tip"). Text (' system error ');}}

Programme II: Later found that this approach has two problems, one is that the user sent the picture is too large, the background did not do compression (backstage colleagues are too busy, in order to accommodate them, we do the front end of compression).

The second is, upload the image after success, the picture is displayed on the IFRAME, this requires a certain reaction time, users will sometimes reflect pictures can not go up, but in fact, the backstage has not returned ...

So I decided to use the Base64 to upload to the backstage way

<input type= "File" id= "Uploadpic" name= "file" >
<label for= "Uploadpic" id= "filebtn" >
+
< IMG class= "showpic" src= "/>
</label>
<span class=" Tip "> Please upload a picture, size within 2M <br/> (picture type can be jpg , jepg,png,gif,bmp) <br/> recommended picture proportions for 640*400</span>
<input type= "text" name= "Turnurl" class= "Turnurl" >
<canvas id= "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); var file = $ (
This) [0].files[0]; if (file.size>2097152) {alert ("Upload picture please less than 2M"); return false;} if (!/image\/\w+/.test (File.type)) {alert ("file must be a picture!")
");
return false;
var reader = new FileReader ();
Reader.readasdataurl (file);
Reader.onload = function (e) {Createcanvas (This.result);}}); function Createcanvas (SRC) {var canvas = document.getElementById ("uploadimg"); var cxt = Canvas.getcontext (' 2d '); canvas
. width = 640;
Canvas.height = 400;
var img = new Image ();
IMG.SRC = src; Img.onload = function () {//var w=img.width;//var h=img.height;//canvas.width= W;//canvas.height=h; Cxt.drawimage (i
MG, 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 of the file information to determine the size of the file file.size, and whether the file is a picture File.type

2. Then through the HTML5 FileReader interface to get the base64 data of this picture

3. This base64 into the canvas, as a picture of SRC, this time you can set the resolution size of the picture, to ensure that the uploaded map is a unified resolution. Of course, you can also follow the original size of the picture.

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

5. Then the background returned to the URL tied to the image of the Data-url property, in the Ajax to hand over the entire form to get this data-url good, so that users can see the fastest time, and the URL is actually still in the process of Ajax to the background

PostScript: These two programs have a problem, will be uploaded to the background a lot of redundant pictures. But backstage colleagues seem to have no opinion, embarrassed.

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

The above is a small set to introduce the project practice a picture upload form or base64 front-end picture compression (front image compression), I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.