js图片压缩+ajax上传

图片压缩用到了localresizeimg 地址: https://github.com/think2011/localResizeIMG

用起来比较简单

 

  <input type="file" id="image1" class="hidden" accept="image/png,image/gif,image/jpeg" /
//图片压缩
$("input:file").change(function () {
        var file = this.files[0];
        lrz(file).then(function (res) {
          //压缩成功
        }).catch(function () {
           //压缩失败
        }).always(function () {
          //成功失败都执行
        })
    });

 

 

完整代码

$("input:file").change(function () {
        var self = $(this);
        var file = this.files[0];
        lrz(file).then(function (res) {
            alert('压缩前' + (file.size / 1024).toFixed(2) + "kb");
            alert('压缩后' + (res.fileLen / 1024).toFixed(2) + "kb");
            var postData = new FormData();
            postData.append("imgfile", res.file);
            postData.append("name", file.name);//解决重命名的问题
            $.ajax({
                url: '/APP/Inventory/UploadImg',
                data: postData,
                type: 'post',
                contentType: false,//禁止修改编码
                processData: false,//不要把data转化为字符
                beforeSend: function () {
                  
                    //加载层
                    layer.open({
                        type: 2,
                        shadeClose: false,
                        content: '上传中...'
                    });
                },
                success: function (data) {
                    data = eval("(" + data + ")");//返回的是json字符串,需要转为json对象
                    if (data.state == 1) {
                        self.prev().children("img").attr("src", res.base64); //预览
                        self.next().val(data.LogMessage);
                    }
                    else {
                        $alertMsg(data.message);
                    }
                },
                error: function () {
                    $alertMsg("上传失败,请重试!");
                },
                complete: function () {
                    console.log("上传结束");
                    layer.closeAll();
                }
            });

        }).catch(function () {
            console.log("失败");
        }).always(function () {
            self.val("");//清空上传控件
           console.log("压缩完毕")
        })
    });

 

后台控制器

 

 public ActionResult UploadImg(HttpPostedFileBase imgfile, string name)
        {
        //
    
        }            

 

posted @ 2019-06-28 16:36  冷瞳ruin  阅读(931)  评论(0编辑  收藏  举报