Use spring mvc + localResizeIMG to implement the function of compressing and uploading HTML5 images,

Source: Internet
Author: User

Use spring mvc + localResizeIMG to implement the function of compressing and uploading HTML5 images,

Recently, I was working on a mobile HTML5 app and used the upload function. At first, I used the traditional upload method to upload photos taken by my mobile phone. Because the photos taken by my mobile phone are usually several MB, therefore, the upload speed is very slow.

I have found the localResizeIMG compression framework on the Internet for a long time. It feels very practical, so I will share it with you here.

Step 1: Download localResizeIMG

Put localResizeIMG in github at https://github.com/think2011/localresizeimg.

Step 2: Import localResizeIMG-related js in the web Project

Decompress localResizeIMG and copy the dist folder in the directory to the project. I put it under the js directory.

Then, import jQuery and localResizeIMG js in your own js. For example:

<span style="white-space:pre">    </span><script src="<c:url value="/js/JQuery/jquery-1.10.0.min.js"/>"></script>  <span style="white-space:pre">    </span><script type="text/javascript" src="<c:url value="/js/lrz/dist/lrz.bundle.js"/>"></script>  

Step 3: add the onchange event in the file box of the uploaded input as follows:

 <input  type="file"  id="payfile" name="myfile" style="display:none;" onchange="fileChange(this)" />

In the fileChange method, code compression and base64 generated after compression are uploaded to the background asynchronously.

Function fileChange (that) {var filepath = $ (that ). val (); if (filepath = "") {return;} var extStart = filepath. lastIndexOf (". "); var ext = filepath. substring (extStart, filepath. length ). toUpperCase (); if (". jpg |. png |. bmp |. jpeg ". toUpperCase (). indexOf (ext. toUpperCase () =-1) {alert ("only images in jpg, png, bmp, and jpeg formats can be uploaded"); return false ;} // compress the image with the image width of 800 lrz (that. files [0], {width: 800 }). then (function (rst) {// asynchronous upload after compression $. ajax ({url: "<% = request. getContextPath () %>/common/fileUploadPicture ", type:" POST ", data: {imgdata: rst. base64 // compressed base Value}, dataType: "json", cache: false, async: false, success: function (data) {if (data. success) {alert (data. message); // data. message is the path of the uploaded file} else {alert (data. message); // data. message is the cause of upload failure }}, error: function () {alert ("Upload Failed ");}});});}

Step 4: spring mvc controller receives base values in the background, parses and saves files

Import sun. misc. BASE64Decoder; // imported base64 class/*** File Upload */@ ResponseBody @ RequestMapping ("common/fileUploadPicture") public Object fileUploadPicture (String imgdata, HttpServletRequest request) {LOGGER.info ("[File Upload (fileUploadPicture)] [params: imgdata =" + imgdata + "]"); BASE64Decoder decoder = new BASE64Decoder (); try {String basePath = request. getRealPath ("/upload_files"); string imgPath = basePath + "/test.jpg"; // a new file object is used to save images, by default, File imageFile = new File (imgPath) is saved in the root directory of the current project. // create the output stream FileOutputStream outputStream = new FileOutputStream (imageFile). // obtain an image File stream, here is the byte [] result = decoder from flex. decodeBuffer (imgdata. split (",") [1]); // decodes for (int I = 0; I <result. length; ++ I) {if (result [I] <0) {// adjust the exception data result [I] + = 256 ;}} outputStream. write (result); return new Result (true, imgPath);} catch (AppException e1) {LOGGER. error ("[File Upload (fileUpload)-fastdfs] [errors:" + e1 + "]"); return new Result (false, "File Upload Failed ");} catch (Exception e) {LOGGER. error ("[fileUpload] [errors:" + e + "]"); return new Result (false, "File Upload Failed");} finally {outputStream. flush (); outputStream. close ();}}

Result class:

import java.io.Serializable;    public class Result implements Serializable{      private static final long serialVersionUID = 1L;      private boolean success;      private String message;        public Result() {          success = true;      }        public Result(boolean success, String message) {          this.success = success;          this.message = message;      }        public boolean isSuccess() {          return success;      }        public void setSuccess(boolean success) {          this.success = success;      }        public String getMessage() {          return message;      }        public void setMessage(String message) {          this.message = message;      }        @Override      public String toString() {          return "Result [success=" + success + ", message=" + message + "]";      }    }  

The above are all the steps. I hope you can leave a message to correct them and support the customer's home.

Related Article

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.