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

Feb 09, 2017 pm 03:56 PM

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)!


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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Table Border in HTML Table Border in HTML Sep 04, 2024 pm 04:49 PM

Guide to Table Border in HTML. Here we discuss multiple ways for defining table-border with examples of the Table Border in HTML.

Nested Table in HTML Nested Table in HTML Sep 04, 2024 pm 04:49 PM

This is a guide to Nested Table in HTML. Here we discuss how to create a table within the table along with the respective examples.

HTML margin-left HTML margin-left Sep 04, 2024 pm 04:48 PM

Guide to HTML margin-left. Here we discuss a brief overview on HTML margin-left and its Examples along with its Code Implementation.

HTML Table Layout HTML Table Layout Sep 04, 2024 pm 04:54 PM

Guide to HTML Table Layout. Here we discuss the Values of HTML Table Layout along with the examples and outputs n detail.

Moving Text in HTML Moving Text in HTML Sep 04, 2024 pm 04:45 PM

Guide to Moving Text in HTML. Here we discuss an introduction, how marquee tag work with syntax and examples to implement.

HTML Ordered List HTML Ordered List Sep 04, 2024 pm 04:43 PM

Guide to the HTML Ordered List. Here we also discuss introduction of HTML Ordered list and types along with their example respectively

HTML onclick Button HTML onclick Button Sep 04, 2024 pm 04:49 PM

Guide to HTML onclick Button. Here we discuss their introduction, working, examples and onclick Event in various events respectively.

HTML Input Placeholder HTML Input Placeholder Sep 04, 2024 pm 04:54 PM

Guide to HTML Input Placeholder. Here we discuss the Examples of HTML Input Placeholder along with the codes and outputs.

See all articles