HTML5 JS compresses the image and obtains the BASE64 encoding of the image for upload,
Basic Process
1) Call reader. readAsDataURL (img) of FileReader to read the selected Image in the onload event.
2) In the onload event of the image object, use the drawImage method of canvas. getContext ('2d ') to resize the Image to the canvas.
3) use the canvas. toDataURL ("image/jpeg", 0.1); Method to convert the image into a base64 string and pass it to the server.
1 var vueImg = new Vue ({2 el: "# divCarImages", 3 data: {model: {carId: '@ carid', imageTitle: '', img64: ''}, images: []}, 4 methods: {5 imageHandle: function () {6 var fup = $ (" # fileImg ") [0]; 7 8 var img = fup. files [0]; 9 10 var image = new Image (); 11 var canvas = $ ("# canvas") [0]; // document. createElement ("canvas"); 12 var ctx = canvas. getContext ('2d '); 13 14 image. onload = function () {15 var w = Image. naturalWidth, 16 h = image. naturalHeight; 17 18 var toSize = 400; 19 canvas. width = toSize; 20 canvas. height = toSize; 21 22 var w2 = toSize, h2 = toSize; 23 if (w> h) {24 h2 = h/w * toSize; 25} else {26 w2 = w/h * toSize; 27} 28 29 ctx. drawImage (image, 0, 0, w, h, 0, 0, w2, h2); 30 31} 32 33 // judge whether the image is 34 if (! Img) {35 return; 36} 37 38 // determine the image format 39 if (! (Img. type. indexOf ('image') = 0 & img. type &&/\.(?: Jpg | png | gif) $ /. test (img. name) {40 alert ('images can only be jpg, gif, png '); 41 return; 42} 43 44 var reader = new FileReader (); 45 46 reader. onload = function (e) {// reader onload start47 var url = reader. result; 48 image. src = url; 49 50} // reader onload end51 52 reader. readAsDataURL (img); 53} 54 55} 56 });
1 function uploadImg () {2 var canvas =$ ("# canvas") [0]; 3 vueImg. model. img64 = canvas. toDataURL ("image/jpeg", 0.1); 4 // $ ("# testMsg" ).html (imgData. length); 5 6 // ajax upload image 7 $. post ("@ Url. content ("~ /AliOss/SaveCarImage ")", vueImg. model, function (ret) {8 9 parseAjaxData (data, function (model) {10 console. log (model. path); 11 alert (model. path); 12 characters ('{showimg'{.html (''); 13}) 14}, 'json'); 15}
Address: http://www.cnblogs.com/ybst/p/6033199.html