使用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, "上传附件为空。"); } }
时间: 2024-10-14 01:03:28