标签:url 不同 creat image 浏览器 led des error ast
使用HttpRequest.Files 获取上传文件,实现上传附件功能,不同浏览器会有差异:
单个文件查看:对应的FileName 是上传文件的原始文件名:例:开发管理手册2017版.docx
单个文件查看:对应的FileName 是上传文件 带路径的文件名 例:C:\\Users\\XXX\\Desktop\\开发管理手册2017版.docx
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, "上传附件为空。"); } }
使用HttpRequest.Files 获取上传文件,实现上传附件功能
标签:url 不同 creat image 浏览器 led des error ast
原文地址:http://www.cnblogs.com/shixl/p/7280149.html