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;
            }
        }

 

 
posted @ 2023-10-09 16:10  Ace001  阅读(213)  评论(0编辑  收藏  举报