HttpContext.Current.Request.Files附件保存
接口实现
/// <summary> /// Post请求,Params传参 /// </summary> /// <param name="url"></param> /// <param name="onHeading"></param> /// <returns></returns> private object PostMobileApiHost(string url, MultipartFormDataContent formData, Action<HttpRequestHeaders> onHeading = null) { using (HttpClient client = new HttpClient()) { try { VerHttps(url); if (onHeading != null) { onHeading.Invoke(client.DefaultRequestHeaders); } HttpResponseMessage response = client.PostAsync(url, formData).Result; if (response.IsSuccessStatusCode) { return response.Content.ReadAsStringAsync().Result; } else { return response.StatusCode; } } catch { throw; } } }
接收附件,使用接口再次调用
HttpFileCollection httpFiles = HttpContext.Current.Request.Files; if (httpFiles != null && httpFiles.Count > 0) { HttpPostedFile file = httpFiles[0]; MultipartFormDataContent from = new MultipartFormDataContent(); //第一个附件,一次仅上传一个文件 byte[] fileBytes = new byte[file.ContentLength]; // 文件内容的字节数组 file.InputStream.Read(fileBytes, 0, file.ContentLength); ByteArrayContent fileContent = new ByteArrayContent(fileBytes); var fileName = file.FileName; fileContent.Headers.ContentType = new MediaTypeHeaderValue(file.ContentType); fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = "file", FileName = fileName }; from.Add(fileContent, "file", fileName); PostMobileApiHost("url", from, OnHeading); }
存储附件
string path = "根路径"; HttpFileCollection httpFiles = HttpContext.Current.Request.Files; List<自定义保存附件类> listAtt = new List<SysAttachment>(); //保存附件 if (httpFiles != null && httpFiles.Count > 0) { if (string.IsNullOrEmpty(path)) { throw new Exception("未设置物理路径地址!"); } //附件分组名称集合 string[] keys = httpFiles.AllKeys; //保存附件列表 for (int i = 0; i < httpFiles.Count; i++) { var postFile = httpFiles[i]; string extension = VerifyExtension(postFile.FileName);//验证后缀名 string newFileName = string.Format("{0}{1}", Guid.NewGuid().ToString(), extension); string newFilePath = string.Format("{0}{1}", "储存路径", newFileName); string savePath = string.Format("{0}{1}", path.TrimEnd('\\'), newFilePath.Replace("/", "\\")); if (FileHelper.FolderExists(string.Format("{0}{1}", path.TrimEnd('\\'), UploadFolder), true)) { //保存附件 postFile.SaveAs(savePath); SysAttachment att = new SysAttachment(); att.ParentId = 0; att.FileName = postFile.FileName; att.FilePath = newFilePath; att.Extension = extension; att.FileSize = postFile.ContentLength.ToString(); att.ContentType = postFile.ContentType; listAtt.Add(att); } } }
标签:string,C#,httpFiles,att,file,new,附件,HttpPostedFile,传值 From: https://www.cnblogs.com/HoFei/p/17914533.html