httpclient上传图片(multipart/form-data)
方式1
string boundary = string.Format("----WebKitFormBoundary{0}", DateTime.Now.Ticks.ToString("x")); MultipartFormDataContent content = new MultipartFormDataContent(boundary); content.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data; boundary=" + boundary); string fileName = Path.GetFileName(picPath); using FileStream fStream = File.Open(picPath, FileMode.Open, FileAccess.Read); content.Add(new StreamContent(fStream, (int)fStream.Length), "file", fileName); using HttpClient client = new HttpClient(); HttpResponseMessage response = client.PostAsync(url, content).Result; if (response.IsSuccessStatusCode) ....
方式2
private void HttpPostFile(string url, string fileFullPath) { using (HttpClient client = new HttpClient()) { var content = new MultipartFormDataContent(); string fileFullName = fileFullPath; string fileName = fileFullName.Substring(fileFullName.LastIndexOf("\\") + 1); content.Add(new ByteArrayContent(System.IO.File.ReadAllBytes(fileFullName)), "file", fileName); var fullResponse = client.PostAsync(url, content).ConfigureAwait(false).GetAwaiter().GetResult().Content.ReadAsStringAsync().Result; } }
作者:xuejianxiyang
出处:http://xuejianxiyang.cnblogs.com
关于作者:Heaven helps those who help themselves.
本文版权归原作者和博客园共有,欢迎转载,但未经原作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。