通過API上傳文件
阿新 • • 發佈:2019-04-26
http bsp read formdata file dia filepath thead accep
客戶端方法
/// <summary> /// 發送post請求,通過API上傳本地文件到服務器 /// </summary> /// <param name="authorCode">API秘鑰</param> /// <param name="url">API上傳地址</param> /// <param name="FilePath">需要上傳的文件本地完整路徑</param> /// <param name="FileName">上傳文件保存的名字</param> /// <returns></returns> public static string HttpPostRequst_UploadFile(string authorCode, string url , string FilePath , string FileName ) { //--------上傳------------ HttpClient client = new HttpClient(); //驗證client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authorCode); //指定類型 client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); #region MultipartFormDataContent form= new MultipartFormDataContent(); StreamContent fileContent = new StreamContent(File.OpenRead(FilePath)); fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data"); fileContent.Headers.ContentDisposition.FileName = FileName; form.Add(fileContent); #endregion HttpResponseMessage res = client.PostAsync(url, form).Result; var uploadModel = res.Content.ReadAsStringAsync().Result; return uploadModel; }
服務器方法
public HttpResponseMessage PostFile( ) { HttpResponseMessage result = null; var httpRequest = HttpContext.Current.Request; if (httpRequest.Files.Count > 0) { var docfiles = new List<string>(); foreach (string file in httpRequest.Files) { var postedFile = httpRequest.Files[file]; var filePath = HttpContext.Current.Server.MapPath("~/" + postedFile.FileName); postedFile.SaveAs(filePath); docfiles.Add(filePath); } result = Request.CreateResponse(HttpStatusCode.Created, docfiles); } else { result = Request.CreateResponse(HttpStatusCode.BadRequest); } return result; }
通過API上傳文件