Home > Web Front-end > H5 Tutorial > Using spring mvc+localResizeIMG to implement HTML5 image compression upload

Using spring mvc+localResizeIMG to implement HTML5 image compression upload

黄舟
Release: 2017-02-09 15:56:19
Original
2163 people have browsed it

Recently I was working on a mobile HTML5 application and used the upload function. At first, I used the traditional upload method to upload photos taken by mobile phones. Since the photos taken by mobile phones are usually several MB,

So the upload speed is very slow.


I found the localResizeIMG compression framework after searching online for a long time. I feel it is very practical, so I would like to share it with you here.

Step 1: Download localResizeIMG

localResizeIMG is placed in github. The address is: https://github.com/think2011/localResizeIMG.

Step 2: Import localResizeIMG related js into the web project
Unzip the localResizeIMG compression and copy the dist folder in the directory to the project. Mine is placed in the js directory.
Then import the js of jQuery and localResizeIMG 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>
Copy after login

Step 3: Add the onchange event to the file box of your uploaded input as follows

In the fileChange method, implement code compression and asynchronously transmit the base64 generated after compression to the background

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("只允许上传jpg、png、bmp、jpeg格式的图片");
			return false;
		}
     //以图片宽度为800进行压缩
	lrz(that.files[0], {
	     width: 800
	   })
	.then(function (rst) {
			//压缩后异步上传
	  		$.ajax({
			url : "<%=request.getContextPath()%>/common/fileUploadPicture",
			type: "POST",
			data : {
				imgdata:rst.base64//压缩后的base值
			},
			dataType:"json",
			cache:false,
			async:false,
			success : function(data) {
			if(data.success)
				{
					alert(data.message);///data.message为上传成功后的文件路径
				}else{
					alert(data.message);///data.message为上传失败原因
				}
							
						},
		error : function(){
				alert("上传失败");
						}
					});
	     });
}
Copy after login

Step 4: The spring mvc controller receives the base value in the background and parses and saves the file

import sun.misc.BASE64Decoder;//导入的base64的类  
/** 
     * 文件上传 
     */  
    @ResponseBody  
    @RequestMapping("common/fileUploadPicture")  
    public Object fileUploadPicture(String imgdata, HttpServletRequest request) {  
        LOGGER.info("[文件上传(fileUploadPicture)][params:imgdata=" + imgdata + "]");  
         BASE64Decoder decoder = new BASE64Decoder();  
        try {  
            String basePath = request.getRealPath("/upload_files");  
            string imgPath=basePath+"/test.jpg";  
            // new一个文件对象用来保存图片,默认保存当前工程根目录  
            File imageFile = new File(imgPath);  
            // 创建输出流  
            FileOutputStream outputStream = new FileOutputStream(imageFile);  
            // 获得一个图片文件流,我这里是从flex中传过来的  
            byte[] result = decoder.decodeBuffer(imgdata.split(",")[1]);//解码  
            for (int i = 0; i < result.length; ++i) {  
                if (result[i] < 0) {// 调整异常数据  
                result[i] += 256;  
            }  
        }  
            outputStream.write(result);  
  
            return new Result(true, imgPath);  
        } catch (AppException e1) {  
            LOGGER.error("[文件上传(fileUpload)-fastdfs][errors:" + e1 + "]");  
            return new Result(false, "文件上传失败");  
        } catch (Exception e) {  
            LOGGER.error("[文件上传(fileUpload)][errors:" + e + "]");  
            return new Result(false, "文件上传失败");  
        }finally{  
        outputStream.flush();   
        outputStream.close();  
          
        }  
    }
Copy after login

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 + "]";  
    }  
  
}
Copy after login

The above is the content of using spring mvc+localResizeIMG to realize HTML5 image compression and uploading. For more related information, please Follow the PHP Chinese website (www.php.cn)!


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template