Js压缩图片后台接收并保存

发布于 2018-05-06  244 次阅读


github地址:https://github.com/think2011/localResizeIMG

function Upload(){
 var fileObj = document.getElementById("FileUpload").files[0]; // js 获取文件对象
 if (typeof (fileObj) == "undefined" || fileObj.size <= 0) {
 alert("请选择图片");
 return;
 }
 lrz(fileObj)
 .then(function (rst) {
 var formFile = new FormData();
 formFile.append("file", rst.base64); //加入文件对象
 rst.formData.append('base64img', rst.base64); // 添加额外参数
 $.ajax({
 url: root.getRoot().url + "/file/uploadWithBase64",
 data: formFile,
 type: "Post",
 dataType: "json",
 async: true, //异步才能调用 xhr 回掉函数
 cache: false,//上传文件无需缓存
 processData: false,//用于对data参数进行序列化处理 这里必须false
 contentType: false, //必须
 success: function (data) {
  //....
 }
 else {
 alert("上传失败");
 }
 },
 //拿到jQuery产生的 XMLHttpRequest对象,为其增加 progress 事件绑定,然后再返回交给ajax使用
 xhr: function () {
 myXhr = $.ajaxSettings.xhr();
 if (myXhr.upload) { // check if upload property exists
 myXhr.upload.addEventListener('progress', function (e) {
 var loaded = e.loaded; //已经上传大小情况
 var total = e.total; //附件总大小
 var percent = Math.floor(100 * loaded / total); //已经上传的百分比
 if (percent == 100) {
 $("#processBar").css("display", "none");
 }
 else {
 $("#processBar").css("display", "block");
 $("#processBar").css("width", percent + "%");
 $("#processBar").html(percent + "%");
 }

 }, false); // for handling the progress of the upload
 }
 return myXhr;
 },
 })
 console.log(rst);
 })
 .catch(function (err) {
 console.log("压缩图片失败");
 })
 .always(function () {
 // 不管是成功失败,都会执行
 });
 }}
 public string UploadWithBase64()
 {
 var result = new Result<string>();
 var imgBase64Data = HttpContext.Current.Request.Form["file"];
 if (!imgBase64Data.Ext_IsNullOrEmpty())
 {
 var data = imgBase64Data.Split(',')[1]; //去掉 data:image的前缀

 byte[] bt = Convert.FromBase64String(data);
 MemoryStream stream = new MemoryStream(bt);
 Bitmap bitmap = new Bitmap(stream);
 // 文件扩展名
 string fileExtension = ".jpeg";
 // 图片名称
 string fileName = Guid.NewGuid().ToString() + fileExtension;
 string path = "/Upload/" + DateTime.Now.ToString("yyyyMM") + "/" + DateTime.Now.ToString("dd") + "/";
 var serverPath = HttpContext.Current.Server.MapPath(path);

 if (!Directory.Exists(serverPath))
 Directory.CreateDirectory(serverPath);
 // 图片上传路径
 string filePath = Path.Combine(serverPath, fileName);
 bitmap.Save(filePath);

 string imgPath = ServerUrl + path + fileName;
 result.Flag = true;
 result.Data = imgPath;
 result.Msg = "上传成功";
 }
 return JsonHelper.ObjectToJson(result);

 }

LoneKing