spring mvc+localResizeIMG实现H5端图片压缩上传

互联网 18-3-26
这次给大家带来spring mvc+localResizeIMG实现H5端图片压缩上传,spring mvc+localResizeIMG实现H5端图片压缩上传的注意事项有哪些,下面就是实战案例,一起来看一下。

最近在做一个移动端HTML5的应用,使用到了上传功能,起初使用传统的上传方式上传手机拍照的照片,由于手机拍照出来的照片一般都是好几MB,所以上传速度是非常慢的。

在网上找了很久找到了localResizeIMG压缩框架,感觉非常的实用,所以在此分享给大家。

第一步:下载localResizeIMG

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

第二步:在web工程中导入localResizeIMG相关js

解压localResizeIMG压缩吧,把目录中的dist文件夹拷贝到工程中,我的是放在js目录下。

然后在自己的js中导入jQuery和localResizeIMG的js。如:

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

第三步:在自己的上传的input的file框加入onchange事件如下代码

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

在fileChange方法中实现代码的压缩和对压缩后生成的base64异步传到后台

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("上传失败");                            }                        });             });    }

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

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();                        }        }

Result类:

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

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

分页查询的使用详解

Node.js如何开发微信墙

以上就是spring mvc+localResizeIMG实现H5端图片压缩上传的详细内容,更多内容请关注技术你好其它相关文章!

来源链接:
免责声明:
1.资讯内容不构成投资建议,投资者应独立决策并自行承担风险
2.本文版权归属原作所有,仅代表作者本人观点,不代表本站的观点或立场
标签: Html5
上一篇:php获取远程图片并下载保存到本地的方法分析 下一篇:移动端H5页面端怎样除去input输入框的默认样式

相关资讯