C# Net Core 使用 HttpClient 上传文件及信息(带Headers,FormData参数)
包:Newtonsoft.Json
public static string UploadFile(byte[] file, string fileName, string token) { Uri uri = new Uri(Appsettings.App("FileServe") + "/file/upload"); using (MemoryStream memoryStream = new MemoryStream(file)) { var formData = new MultipartFormDataContent(); formData.Headers.Add("Access-Token", token); formData.Add(new StreamContent(memoryStream, (int)memoryStream.Length), "file", fileName); //Region为请求文件接口需要的参数,根据调用接口参数而定 //formData.Add(new StringContent(info.Region), "Region"); var _httpclient = new HttpClient(); var response = _httpclient.PostAsync(uri, formData).Result; if (response.IsSuccessStatusCode) { var responseStr = response.Content.ReadAsStringAsync().Result; JObject o = JObject.Parse(responseStr); //var responseObj = JsonConvert.DeserializeObject<string>(responseStr); if (o.ContainsKey("id")) { var id = o.GetValue("id").ToString(); return id; } else { throw new Exception("上传文件时出错,错误信息为:" + responseStr); } } } return string.Empty; }