因為項目需要,結合之前的項目使用的Uploadifive上傳做了點小小的拓展。
var YSHT = (function ($, ysht) { ysht.UploadFiles = function (options) { var defaults = { element: "input[type='file']", auto: true, //是否自動上傳 buttonText: "附件上傳", //定義顯示在按鈕上的文本 fileSizeLimit: "20GB",//上傳文件大小限制 uploadLimit: 999, //上傳文件個數 width: 100, height:34, formData: {}, callback: null, multi: false, url: "", removeCompleted:true }; var opts = $.extend({}, defaults, options); if (!opts.url) { alert("初始化上傳控件發生錯誤!"); return false; } if (!$(opts.element).attr("id")) { alert("初始化上傳控件發生錯誤!"); return false; } var files = []; var uploadify = $(opts.element).uploadifive({ auto: opts.auto, width: opts.width, height: opts.height, buttonClass: "btn btn-primary", buttonText: "<i class=\"fa fa-upload\"></i> " + opts.buttonText, dnd: false, //禁用拖拽上傳功能 fileSizeLimit: opts.fileSizeLimit, fileType: true, //允許所有的文件類型(允許所有圖片'image/*') method: "post", multi: opts.multi, removeCompleted: opts.removeCompleted,//是否移除從隊列張完成上傳的項目 formData: opts.formData, uploadLimit: opts.uploadLimit, uploadScript: opts.url, onError: function (res) { alert(res.errMsg); return false; }, onUploadComplete: function (file, res) { res = JSON.parse(res); var html = "<div class = 'img-view'><img class = 'previewImg previewImg_1' width='200' height='200' src=''"; html += "serverFilePath = '" + res.FilePath + "'"; html += "fileName = '" + res.FileName + "'"; html += "fileExt='" + res.FileExt + "'/>"; html += "<a class='img-del' del-path='" + res.FilePath + "'"; html += "filename = '" + res.FileName + "'fileext='" + res.FileExt + "'>刪除</a></div>"; $("#preview").append(html) var imgArray = document.getElementById("preview").getElementsByTagName("img"); var finallyImg = document.getElementById("preview").getElementsByTagName("img")[imgArray.length - 1]; $(finallyImg).siblings('a').attr({ 'del-path': res.FilePath, "fileName": res.FileName, fileExt: res.FileExt }); var reader = new FileReader(); var path = res.SavePath; reader.readAsDataURL(file); reader.onload = function (e) { url = reader.result; finallyImg.src = url; $("#resultImage")[0].src = url; }; } }); //RETURN { // uPLOADIFY: UPLOADIFY, // fILES: FILES //}; }; return ysht; }(jQuery, window.YSHT || {}));
后台代碼分為壓縮上傳和不壓縮上傳,其中壓縮上傳的方法是在網上找了個大神寫的。因為是改別人的代碼,很多寫的很亂地方沒有改的完善,有空需要好好整理一下
/// <summary> /// 未壓縮上傳 /// </summary> /// <param name="mfile"></param> /// <returns></returns> [HttpPost] public ActionResult NotCompressUploadImg(HttpPostedFileBase mfile) { try { if (mfile != null) { string fileName = Path.GetFileName(mfile.FileName);// 原始文件名稱 string fileExtension = Path.GetExtension(fileName); // 文件擴展名 string saveName = Guid.NewGuid() + fileExtension; // 保存文件名稱 這是個好方法。 string savepath = Server.MapPath("../ImageTemp/") + fileName; mfile.SaveAs(savepath); if (IsPicture(savepath) == 1) { return Json(new { Success = false, Message = "該圖發現木馬文件!" }, JsonRequestBehavior.AllowGet); } else { var path = "/Upload/Image/"; var uploadpath = Server.MapPath("~" + path); if (!Directory.Exists(uploadpath)) { Directory.CreateDirectory(uploadpath); } //string saveName = Encrypt.GenerateOrderNumber() + fileExtension; // 保存文件名稱 這是個好方法。 mfile.SaveAs(uploadpath + saveName); var fullPath = uploadpath.Replace("\\", "/") + saveName; return Json(new { Success = true, FilePath = path + saveName, FileName = fileName, FileExt = fileExtension, SavePath = fullPath, Message = "上傳成功!" }); } } return Json(new { Success = false, Message = "請選擇要上傳的文件!" }, JsonRequestBehavior.AllowGet); } catch (Exception ex) { return Json(new { Success = false, Message = ex.Message }, JsonRequestBehavior.AllowGet); } }
public ActionResult CompressImgBase64Uploadfinal(HttpPostedFileBase mfile) { try { if (mfile != null) { //先保存到臨時文件夾,如果是病毒,就刪除s string fileName = Path.GetFileName(mfile.FileName);// 原始文件名稱 string fileExtension = Path.GetExtension(fileName); // 文件擴展名 string saveName = Guid.NewGuid() + fileExtension; // 保存文件名稱 這是個好方法。 string savepath = Server.MapPath("../ImageTemp/") + fileName; mfile.SaveAs(savepath); var readpath = savepath.Replace("\\", "/"); System.Drawing.Image img = new System.Drawing.Bitmap(readpath); if (IsPicture(savepath) == 1) { return Json(new { Success = false, FilePath = "", FileName = "", FileExt = ".jpg", Message = "上傳的圖片有病毒!" }); } var path = "/Upload/Image/"; var uploadpath = Server.MapPath("~") + path; if (!Directory.Exists(uploadpath)) { Directory.CreateDirectory(uploadpath); } string savepath1 = uploadpath + saveName; //圖片壓縮上傳 bool isSuccess = ReduceImage(img, savepath1, 50); if (isSuccess) { System.IO.File.Delete(savepath); return Json(new { Success = true, FilePath = path + saveName, FileName = fileName, FileExt = ".jpg", Message = "上傳成功!" }); } } return Json(new { Success = false, FilePath = "", FileName = "", FileExt = "", Message = "上傳失敗!" }); ; } catch (Exception ex) { return Json(new { Success = false, Message = ex.Message }, JsonRequestBehavior.AllowGet); } }
/// <summary> /// 壓縮圖片並保存 /// </summary> /// <param name="iSource">圖片文件</param> /// <param name="outPath">文件保存路徑</param> 例如 var outPath = Path.Combine(Request.MapPath("~/Upload"), Path.GetFileName(file.FileName)); /// <param name="flag">值越大代表圖片質量越好,一般默認控制在50為最佳壓縮質量</param> /// <returns></returns> public static bool ReduceImage(Image iSource, string outPath, int flag) { ImageFormat tFormat = iSource.RawFormat; EncoderParameters ep = new EncoderParameters(); long[] qy = new long[1]; qy[0] = flag; EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy); ep.Param[0] = eParam; try { ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageDecoders(); ImageCodecInfo jpegICIinfo = null; for (int x = 0; x < arrayICI.Length; x++) { if (arrayICI[x].FormatDescription.Equals("JPEG")) { jpegICIinfo = arrayICI[x]; break; } } if (jpegICIinfo != null) iSource.Save(outPath, jpegICIinfo, ep); else iSource.Save(outPath, tFormat); return true; } catch { return false; } finally { iSource.Dispose(); } }