圖片壓縮用到了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)
{
//
}
