使用HttpRequest.Files 獲取上傳文件,實現上傳附件功能,不同瀏覽器會有差異:
- 獲得在 Google 瀏覽器上傳后得到的 HttpRequest.Files (客戶端上載文件的集合)
單個文件查看:對應的FileName 是上傳文件的原始文件名:例:開發管理手冊2017版.docx
- 獲取IE瀏覽器上傳后HttpRequest.Files:
單個文件查看:對應的FileName 是上傳文件 帶路徑的文件名 例:C:\\Users\\XXX\\Desktop\\開發管理手冊2017版.docx
- 因為不同瀏覽器對應的FileName不一致,在保存文件的時候,需要對FileName 進行處理:(僅獲取文件名)
string aFirstName = aFile.Substring(postedFile.FileName.LastIndexOf("\\") + 1, (postedFile.FileName.LastIndexOf(".") - aFile.LastIndexOf("\\") - 1));
[HttpPost, Route("PostFile")] public ResponeResult<List<FileModel>> PostFile() { var result = new ResponeResult<List<FileModel>>(PromptCode.SUCCESS, "附件上傳成功。"); string[] allowExtension = { ".doc", ".docx", ".xls", ".xlsx", ".pdf", ".zip", ".rar", ".jpg", ".png", ".gif" }; var httpRequest = HttpContext.Current.Request; List<FileModel> docfiles = new List<FileModel>(); if(httpRequest.Files.Count > 0) { var date = DateTime.Now.ToString("yyyy-MM-dd"); var relativePath = string.Format("/Upload/Contract/{0}/", date); var path = HttpContext.Current.Server.MapPath(@"~" + relativePath); if(!Directory.Exists(path))//判斷是否存在 { Directory.CreateDirectory(path);//創建新路徑 } FileModel mode = null; foreach(string file in httpRequest.Files) { var postedFile = httpRequest.Files[file]; string fileType = System.IO.Path.GetExtension(postedFile.FileName); if(string.IsNullOrEmpty(fileType)) { continue; } var rs = allowExtension.Contains(fileType.ToLower()); if(!rs) continue; //對文件名處理 var aFile = postedFile.FileName; string aFirstName = aFile.Substring(postedFile.FileName.LastIndexOf("\\") + 1, (postedFile.FileName.LastIndexOf(".") - aFile.LastIndexOf("\\") - 1)); string strGuid = Guid.NewGuid().ToString(); //保存文件名 var fileName = "file_" + strGuid + fileType; var filePath = path + fileName; postedFile.SaveAs(filePath); var webHostConfig = ConfigurationManager.AppSettings["WebHostDomain"]; var webPath = string.Format("http://{0}{1}{2}", string.IsNullOrEmpty(webHostConfig) == true ? HttpContext.Current.Request.Url.Authority : webHostConfig, relativePath, fileName ); mode = new FileModel(); mode.FileId = strGuid; mode.FileName = aFirstName + fileType; mode.FilePath = filePath; mode.WebPath = webPath; mode.RelativePath = relativePath + fileName; mode.CreateTime = DateTime.Now; mode.CreateUser = Session.UserId; docfiles.Add(mode); } if(!this.fileService.BatchAdd(docfiles)) { return new ResponeResult<List<FileModel>>(PromptCode.ERROR, "上傳附件保存失敗,請聯系管理員。"); } var filedata = docfiles; result.Data = filedata; return result; } else { return new ResponeResult<List<FileModel>>(PromptCode.ERROR, "上傳附件為空。"); } }