1

I'm uploading an image.

I want to set the value of Content-Type="multipart/form-data; boundary=----WebKitFormBoundaryFoxUxCRayQhs5eNN"

using the code :

HttpRequestMessage request=new HttpRequestMessage();
request.Content.Headers.ContentType="multipart/form-data; boundary=----WebKitFormBoundaryFoxUxCRayQhs5eNN";

or request.Header.ContentType="multipart/form-data; boundary=----WebKitFormBoundaryFoxUxCRayQhs5eNN";

it will cause an error:one of the identified items was in an invalid format.

if only set of "multipart/form-data" it will be ok but can not upload the file.

How to set it?

打玻璃
  • 413
  • 4
  • 13

1 Answers1

1

Here are some code snippets you can refer to:

  using (var client = new HttpClient())
  using (var fileStream = File.Open(fileName, FileMode.Open, FileAccess.Read)
  using (var streamContent = new StreamContent(fileStream))
  {
     streamContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data");
     streamContent.Headers.ContentDisposition.Name = "\"file\"";
     streamContent.Headers.ContentDisposition.FileName = "\"" + fileName + "\"";
     streamContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
     string boundary = "WebKitFormBoundaryFoxUxCRayQhs5eNN";

     var fContent = new MultipartFormDataContent(boundary);
     fContent.Headers.Remove("Content-Type");
     fContent.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=" + boundary);
     fContent.Add(streamContent);

     var response = await client.PostAsync(new Uri(url), fContent);
     response.EnsureSuccessStatusCode();
  }

if you use HttpWebRequest,you could refer to this:https://stackoverflow.com/a/20000831/10768653

Leo Zhu - MSFT
  • 12,617
  • 1
  • 3
  • 17
  • no but it can not upload the image to php api while I send it right using HttpWebRequest in c# – 打玻璃 Jun 28 '19 at 12:05
  • 1
    Don't dispose HttpClient. HttpClient is meant to be reused. More information here: https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/ And here: https://josefottosson.se/you-are-probably-still-using-httpclient-wrong-and-it-is-destabilizing-your-software/ – Brandon Minnick Jun 29 '19 at 16:43
  • 1
    @daotian does the server receive the request correctly? In addition, if you use HttpWebRequest, you can refer to the above link – Leo Zhu - MSFT Jul 01 '19 at 01:30