Home > Web Front-end > H5 Tutorial > spring mvc+localResizeIMG implements H5 image compression and uploading

spring mvc+localResizeIMG implements H5 image compression and uploading

php中世界最好的语言
Release: 2018-03-26 13:17:18
Original
2638 people have browsed it

This time I will bring you spring mvc+localResizeIMG to realize H5-side image compression and upload. Spring mvc+localResizeIMG realizes H5-side image compression and upload. What are the precautions? What are the practical cases? Let’s take a look. one time.

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, the upload speed is very fast. slow.

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

Step one: Download localResizeIMG

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

Second step: Import localResizeIMG related js in the web project

Decompress localResizeIMG compression and copy the dist folder in the directory to In 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

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

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 background receives the base value 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

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Detailed explanation of the use of paging query

How to develop WeChat wall with Node.js

The above is the detailed content of spring mvc+localResizeIMG implements H5 image compression and uploading. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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