public ActionResult FileUpload2() { try { UploadModel model = new UploadModel(); var result = new { Flag = false, Message = "上传文件失败。" }; if (this.Request.Files.Count > 0) { var file = this.Request.Files[0]; if (file.ContentLength > 1024 * 1024 * 2) { model.ReturnFlag = false; model.Message = "文件不能大于2M!"; } else { model = ChatHelper.UploadFile(file, UNCConfig.GetCfg()); } } else { model.ReturnFlag = false; model.Message = "找不到可以上传的文件!"; } string jsonData = JsonConvert.SerializeObject(model); ViewData["r"] = jsonData; } catch (Exception ex) { throw ex; } return(PartialView()); }
/// <summary> /// 上传文件 /// </summary> public static UploadModel UploadFile(HttpPostedFileBase file, UNCConfig cfg) { UploadModel model = new UploadModel(); List <string> enabledTypes = new List <string>() { "image/pjpeg", "image/x-png", "image/bmp", "image/png", "image/jpeg" }; //model.FileName = string.Format("{0}.jpg{1}", file.ContentLength, Path.GetExtension(file.FileName)); model.FileName = string.Format("{0}.jpg", file.ContentLength, Path.GetExtension(file.FileName)); model.FileSize = ChatHelper.FormatFileSize(file.ContentLength); model.ReturnFlag = false; if (!enabledTypes.Exists(type => type == file.ContentType)) { model.Message = "上传失败:不支持的文件格式。(仅支持.jpg|.png|.bmp格式)"; } else { string fileServer = System.Configuration.ConfigurationManager.AppSettings["fileServer"]; try { using (UNCAccessWithCredentials unc = new UNCAccessWithCredentials()) { if (unc.NetUseWithCredentials(cfg.UNCPath, cfg.User, cfg.Domain, cfg.Password)) { var now = DateTime.Now; var yyyyMM = now.ToString("yyyyMM"); var yyyyMMdd = now.ToString("yyyyMMdd"); var dir = cfg.UNCPath + "\\" + yyyyMM + "\\" + yyyyMMdd + "\\"; var filename = Utils.SHA1Stream(file.InputStream) + ".jpg"; if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } file.SaveAs(dir + filename); model.FileName = Path.GetFileName(file.FileName); model.FileUrl = fileServer + yyyyMM + "/" + yyyyMMdd + "/" + filename; model.ReturnFlag = true; model.Message = "上传成功。"; } else { model.Message = "上传失败,错误代码:" + unc.LastError; } } } catch (Exception ex) { model.Message = ex.Message; } } return(model); }