使用spring mvc+localResizeIMG实现HTML5端图片压缩上传

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_34845394/article/details/78918217

第一步:下载localResizeIMG

localResizeIMG放在github中的,地址是:https://github.com/think2011/localResizeIMG

第二步:在web工程中导入localResizeIMG相关js
解压localResizeIMG压缩吧,把目录中的dist文件夹拷贝到工程中,我的是放在js目录下。
然后在自己的js中导入jQuery和localResizeIMG的js。如:

<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="js/lrz.bundle.js"></script>

第三步:在自己的上传的input的file框加入onchange事件如下代码
在fileChange方法中实现代码的压缩和对压缩后生成的base64异步传到后台

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title></title>
	</head>
	<body>
		<p>图片压缩上传案例</p>


		<input type="file" id="payfile"/>
		<input type="button" value="压缩后上传"  onclick="fileChange()"/>


		<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
		<script type="text/javascript" src="js/lrz.bundle.js"></script>
		
		
		<script type="text/javascript">
			function fileChange() {
				var img = document.getElementById('payfile');
				//以图片宽度为800进行压缩
				lrz(img.files[0],{
					width:500,
					height:500
				}).then(function(rst) {
					var img = rst.base64;
					//压缩后异步上传
					$.post({
						url: "http://192.168.1.112:8085/NewHRHServer/common/images/fileUploadPicture",
						data: {
							imgdata: img //压缩后的base值
						},
						success: function(data) {
							alert(data)
						},error:function(data){
							console.log(data)
						}
					});
				});
			}
		</script>
	</body>

</html>

第四步:spring mvc controller 后台接收base值并解析并保存文件

@RequestMapping("/fileUploadPicture") 
	public void uploadImg(String imgdata, HttpServletResponse response) throws IOException {

		BASE64Decoder decoder = new BASE64Decoder();
		String imgPath = SysConfig.avatarsDir + "/1112.jpg"; 

		// new一个文件对象用来保存图片,默认保存当前工程根目录 
		File imageFile = new File(imgPath); 
		// 创建输出流 
		FileOutputStream outputStream;
		try {
			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); 
			PrintWriter pw = response.getWriter();
			pw.write("success");
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	}



猜你喜欢

转载自blog.csdn.net/qq_34845394/article/details/78918217
今日推荐