简介
用户需求,通过 multipart/form-data 类型 HTTP 请求上传文件,原帮助类代码参考 WebApi 帮助类,修改代码发送 HttpClient 表单文件上传请求。
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
|
public static string CreatePostHttpClient(string url, string requestUrl) { try { string filePath = "1.jpg"; string savePath = "/danger/reform/before/";
HttpClient httpClient = new HttpClient(); httpClient.BaseAddress = new Uri(url); MultipartFormDataContent form = new MultipartFormDataContent(); FileStream fs = File.OpenRead(filePath); var streamContent = new StreamContent(fs); var imageContent = new ByteArrayContent(streamContent.ReadAsByteArrayAsync().Result); imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data"); form.Add(imageContent, "file", Path.GetFileName(filePath)); form.Add(new StringContent(savePath), "path");
var result = httpClient.PostAsync(requestUrl, form).Result; return result.Content.ReadAsStringAsync().Result; } catch (Exception ex) { TXTHelper.Logs(ex.ToString()); return ""; } }
|