压缩上传图片

图片压缩旋转,我是用了html5ImgCompress,处理图片压缩、旋转、输出base64

地址:https://github.com/mhbseal/html5ImgCompress

 $('#imgUpdown').on('change', function (e) {
        new html5ImgCompress(e.target.files[0], {
            before: function (file) {
                console.log('单张: 压缩前...');
            },
            done: function (file, base64) {
                console.log('单张: 压缩成功...');
                // insertImg(file); // 显示原图

                var fd = new FormData();
                fd.append('user_id', user_id);
                fd.append('file', convertBase64UrlToBlob(base64), file.name);
                fd.append('filename', file.name);


                $.ajax({
                    url: api,
                    method: 'POST',
                    processData: false, // 必须
                    contentType: false, // 必须
                    dataType: 'json',
                    data: fd,
                    success(data) {
                        console.log(data);
                        window.location.href = 'result.html?user_id='+data.data.id;
                    }
                });
            },
            fail: function (file) {
                console.log('单张: 压缩失败...');
            },
            complete: function (file) {
                console.log('单张: 压缩完成...');
            },
            notSupport: function (file) {
                alert('浏览器不支持!');
            }
        });
    });

用formData 格式提交

因为base64,给后端占用空间太大,所以要转成blod 的格式

这里需要用到base64转成blod 

有现成的方法:

function convertBase64UrlToBlob(urlData){

        var bytes=window.atob(urlData.split(',')[1]);        //去掉url的头,并转换为byte

        //处理异常,将ascii码小于0的转换为大于0
        var ab = new ArrayBuffer(bytes.length);
        var ia = new Uint8Array(ab);
        for (var i = 0; i < bytes.length; i++) {
            ia[i] = bytes.charCodeAt(i);
        }

        return new Blob( [ab] , {type : 'image/png'});
    }

****

需要注意的是blod 对象加入formDate,需要第三个参数,文件名称

详情可参考


原文地址:https://www.cnblogs.com/niubenbit/p/7410654.html