JavaScript图片业务处理

2017-01-12 - 47 Views - 0 Goods - 4 条评论

前言

在公司项目,遇到一个问题,就是用户在咨询或者咨询的时候,可以上传文字和图片。

当我尝试文字和图片上传的时候,发现结果真的不理想(主要是form表单提交或者form-data),遇到一堆问题。

然后采取的是:

用户点击上传图片即可上传到服务器,问题描述(文字)是点击提交按钮将把数据提交到服务器。

业务

图片上传用的是input file上传,然后有个div可以看到用户上传的缩略图。

其实是限制图片大小为5M,这个简单,直接判断上传文件的大小。

在其次就是现在用户上传的文件格式类型:我这里使用的是截取字符串来判断,判断用户上传的文件,根据xxxx.xxx的[.]来截取后面的字符串(这个是最后一个点),然后再判断所谓的非png.jpg,gif等等就行了。

图片压缩,主要是考虑到节省流量,就我一个iPhone随便一张图片都是3M~5M,实在是太大。本来想使用HTML5的Canvas来绘制图片,发现用户体验不咋的...于是用了第三方的JS图片压缩库:localResizeIMG.效果还不错,3M的图片压缩成240kb,压缩率挺高的。

最后就是图片如何提交给后台:由于我这儿图片在浏览器显示base64加密的数据,所以直接post方式传到后台。例如:


data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAoHBwgHBgoICAgLCgoLDhgQDg0NDh0VFhEYIx8lJCIfIiEmKzcvJik0KSEiMEExNDk7Pj4+JS5ESUM8SDc9Pjv/2wBDAQoLCw4NDhwQEBw7KCIoOzs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozv/wAARCABkAGQDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t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8jaScZKnJ6jIGK1T4f8Xy6pqcl9p7G2v/kjjRkG8LkKGIPyjbnJ7kiuCl1K9bZ/pt58qgZF3I2TknI5469PanLrOrKu1dTvRnqPtL/rzS5WPmNfWNEhg1CPS7IXSkfv3+1IFyNuAFHoADnJ44HaqN7pMVomWknWRgCkcqffUHGFI6g5zx0xWfLe30twLh7u4aYAhZGkJZRgDgnkcDFI19dM0ZaaTMbAqdx+XB4AHbHP51WyJau7m5pcum6RCL24W6hlZDGyq4ZWJGPmGARgkE8nrzWdNfNBta1GFZWBLqDkMMHAPQEEYzyMVe0zxDbySNDqcURRiCJDDuJ65UgDocDBxxisZmUlsjynJLAI/wApBOQMEY4GAADmm7W0Fr1JoriTZjYjbTjpRVdRjIKgEdsUVNx2H3ESgQ9eYzn8zTIYVZs5YH2NFFMOhvaVpFtdW08khfMf3QCAP5VjsM5GfWiiqJGeWvHWjy1/SiikBfvrOGG10ySNdrT2YkkIP3m3uM/kBVTyl9/zoooGNMSkc5/OojEuTyfzoopAhpiUihwZDuZiTgD8hRRSKLNrAhjOR3/oKKKKBH//2Q==

后台解码URL,然后再把base64转换jpg格式图片,发现是灰色背景或者是已损坏的图片...然后就困扰了俩三天了。

之后找到解决方案了,应该后端把data:image/jpeg;base64,给解析乱了,导致图片各种损坏。所以前端在发送数据,只发送截取data:image/jpeg;base64,后面的数据即可,另外包括图片名,这样可以判断图片类型。

源码


<div id="complaints-conten-input-per" class="mui-input-row" style="display: block">
    <textarea id="textarea1" rows="5" placeholder="问题描述"></textarea>
    <div class="complaints-conten-photo">
        <div class="complaints-conten-photo-title">添加照片</div>
        <form id="imgForm_1" enctype="multipart/form-data">
            <div class="complaints-conten-photo-images">
                <input id="photo1" type="file" name="file1" class="mui-btn mui-btn-block complaints-conten-photo-images-info"/>
                <div id="click1" class="clickImg"
                     style="width: 80px; height: 80px; position: absolute; z-index: -1; border: 1px solid #bbb;left: 10px"></div>
                <input id="photo2" type="file" name="file2" class="mui-btn mui-btn-block complaints-conten-photo-images-info"/>
                <div id="click2" class="clickImg"
                     style="width: 80px; height: 80px; position: absolute; z-index: -1; border: 1px solid #bbb;left: 100px;"></div>
                <input id="photo3" type="file" name="file3" class="mui-btn mui-btn-block complaints-conten-photo-images-info"/>
                <div id="click3" class="clickImg"
                     style="width: 80px; height: 80px; position: absolute; z-index: -1; border: 1px solid #bbb;left: 190px;"></div>
                <input id="photo4" type="file" name="file4" class="mui-btn mui-btn-block complaints-conten-photo-images-info"/>
                <div id="click4" class="clickImg"
                     style="width: 80px; height: 80px; position: absolute; z-index: -1; border: 1px solid #bbb;left: 280px;"></div>
            </div>
        </form>
    </div>
    <input type="submit" class="mui-btn mui-btn-orange" onclick="sub();" value="提交1" />
</div>

<script type="text/javascript">
    //循环且输出遍历按钮
    for (var i = 1; i < 9; i++) {
        var comp1 = 'photo' + i;
        var comp2 = 'click' + i;
        //输出图片点击上传预览
        document.write('<script type="text/javascript">' +
            'document.getElementById("' +
            comp1 +
            '").addEventListener("change", function (e) {' +
            'var files=this.files;' +
            'var img=new Image();' +
            'var reader=new FileReader();' +
            'var fileName = ' +
            comp1 +
            '.value;' +
            '/*图片压缩START*/' +
            'lrz(this.files[0]).then(function (rst) {' +
            'console.log("图片压缩详细输出信息:");console.log(rst);' +
            'console.log("图片压缩后Base64输出:");console.log(rst.base64);' +
            'reader.readAsDataURL(files[0]);' +
            'reader.onload=function(e){' +
            'var mb=(e.total/1024)/1024;' +
            'if(mb>=5){' +
            'mui.alert("上传的照片不可以大于5M,请重新上传","照片上传");' +
            'return' +
            '}' +
            'if(fileName.length > 1 && fileName ) {' +
            'var ldot = fileName.lastIndexOf(".");' +
            'var type = fileName.substring(ldot + 1);' +
            'if( (type != "jpg") && (type != "png") && (type != "gif")&&(type != "bmp") && (type != "jpeg") ) {' +
            'mui.alert("请上传标准图片格式文件","照片上传");' +
            'return' +
            '}' +
            '}' +
            'img.src=this.result;' +
//            '/*未压缩*/' +
//            'imgSrc = img.src;' +
//            'console.log("用户上传图片:" + imgSrc);' +
            '/*已压缩*/' +
            'imgSrc = rst.base64;' +
            'console.log("用户上传图片(已压缩):" + imgSrc);' +
            'console.log("用户上传图片:" + rst.origin.name);' +
            '' +
            '/*截取字符串*/' +
            'var imgIndex = imgSrc.lastIndexOf(",");' +
            'var imgBase64 = imgSrc.substring(imgIndex + 1);' +
            'console.log("截取后字符串:" + imgBase64);' +
            '/*后台接收参数上传 */' +
//          'alert(decodeURIComponent(imgSrc));' +
            'mui.post("http://192.168.0.112:8080/module1/FileUpload/mobile/fileUpload",{' +
            'userId: 2,' +
            'type: 1,' +
            'fileName: rst.origin.name,' +
            'base64ImgData: imgBase64' +
            '},function(data){' +
            '/*if (data.code == "200") {mui.toast("图片上传失败,请稍后或者重新上传")}*/' +
            '},"json"' +
            ');' +
            'img.style.width="100%";' +
            'document.getElementById("' +
            comp2 +
            '").style.width="80px";' +
            'document.getElementById("' +
            comp2 +
            '").style.height="80px";' +
            'document.getElementById("' +
            comp2 +
            '").innerHTML="";' +
            'document.getElementById("' +
            comp2 +
            '").appendChild(img)};' +
            '});' +
            '/*图片压缩END*/' +
            '});' +
            '</script>'
        );
    }
</script>
转载请注明原文链接:首页 -> 学习 -> JavaScript图片业务处理
  • 支付宝打赏
  • 微信打赏

江苏-淮安

永远年轻,永远热泪盈眶。