question

DaniloS-7258 avatar image
0 Votes"
DaniloS-7258 asked gilsonribeiro-8256 commented

HttpClient MultiPart form file upload

Hi,

I am not very experienced in developing using ReST and I have been trying to upload a file using HttpClient and multipart form. In the form there is also a data part, the upload using Postman works and it generates the following content:

------WebKitFormBoundary7MA4YWxkTrZu0gW

Content-Disposition: form-data; name="data";
Content-Type: application/json

{"type":"componentElectronic","properties":{"recCode":"A-0000037","label":"file.pdf"}}

------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="file"; filename="file.pdf"
Content-Type: application/octet-stream
Content-Transfer-Encoding: base64

JVBERi0xLjcNJeLjz9MNCjIwNDYg....DAwMDAwMDAwMCA2NTUzNSBmDQp0cmFpbGVyDQo8PC9TaXplIDIwNDY+Pg0Kc3RhcnR4cmVmDQoxMTYNCiUlRU9GDQo=

------WebKitFormBoundary7MA4YWxkTrZu0gW--

I have been trying with variations of the following code:

static public ComponentResponse CreateFileRecord(string url, string username, string password, ComponentRequest theComponent, string fullFilePath)

  {
      ComponentResponse reference = null;
      using (var httpClient = new HttpClient())
      {
          var authToken = Encoding.ASCII.GetBytes($"{username}:{password}");
          httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(authToken));
          httpClient.DefaultRequestHeaders.Add("X-Requested-By", "AM-Request");
          MultipartFormDataContent mpform = new MultipartFormDataContent();
          //add string content part
          JsonSerializerSettings jsonSettings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };
          var json = JsonConvert.SerializeObject(theComponent, jsonSettings);
          var body = new StringContent(json, Encoding.UTF8, "application/json");
          body.Headers.Add("Content-Disposition", "form-data; name=\"data\"");
          mpform.Add(body);
          //add file part
          using (FileStream fs = File.OpenRead(fullFilePath))
          {
              using (var streamContent = new StreamContent(fs))
              {
                  var fileContent = new ByteArrayContent(streamContent.ReadAsByteArrayAsync().Result);
                  fileContent.Headers.Add("Content-Disposition", "form-data; name=\"file\"");
                  fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
                  mpform.Add(fileContent, "file", Path.GetFileName(fullFilePath));
                  var response = httpClient.PostAsync(url, mpform).Result;
                  string result = response.Content.ReadAsStringAsync().Result;
                  responseText = response.StatusCode + ":" + response.ReasonPhrase;
                  reference = JsonConvert.DeserializeObject<ComponentResponse>(result);
              }
          }
      }
      return reference;
  }

but for some reason, I always get an internal server 500 exception. Would anyone have any suggestions on what I am doing wrong?

Thank you for the help

dotnet-csharp
· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

using (var httpClient = new HttpClient())
{
FileInfo arquivoInfo = new FileInfo(arquivo);
httpClient.DefaultRequestHeaders.Add("X-Requested-By", "AM-Request");
MultipartFormDataContent mpform = new MultipartFormDataContent();
string Name = arquivoInfo.FullName;
JsonSerializerSettings jsonSettings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };
var json = JsonConvert.SerializeObject(js, jsonSettings);
using (FileStream fs = File.OpenRead(Name))
{
using (var streamContent = new StreamContent(fs))
{
var fileContent = new ByteArrayContent(streamContent.ReadAsByteArrayAsync().Result);
mpform.Add(fileContent, "anexos", Path.GetFileName(Name));
var response = httpClient.PostAsync(url, mpform).Result;
}
}

                 }
0 Votes 0 ·

My code worked like this

0 Votes 0 ·
DaniloS-7258 avatar image
1 Vote"
DaniloS-7258 answered

there were a couple of things wrong but essentially the real problem was a boundary issue that could not be identified because error 500 did not contain a reason in the message. Anyway, thanks for the help

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

karenpayneoregon avatar image
0 Votes"
karenpayneoregon answered DaniloS-7258 commented

One problem may be the file is too large and needs HttpRuntime maxRequestLength to be set, as per the following page.

Perhaps using Fiddler composer to perform the upload might help pinpoint the error.


· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

that's a great idea, I didn't think of that. I will try it, thank you

0 Votes 0 ·
TimonYang-MSFT avatar image
0 Votes"
TimonYang-MSFT answered TimonYang-MSFT commented

The internal server 500 exception is a broad error, indicating that there is a problem with the website's server, but the server can't more accurately explain the exact problem.

If the service provider is using IIS, the error may be more specific:

5xx - Server error

The web server is too busy, the configuration data is invalid or even the uploaded file is too large (default 4MB) may cause this error.

I think you may need to contact the service provider, only they can know what specific exception has occurred.


If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

hi, thanks for the reply, but when using Postman the call works, it's exactly the same call, with the same data and file. Therefore there must be an error in my code in structuring the request.

Up to line 12, the call should be fine because I use the same code in other calls that do not require the use of multi-part forms and they work. The error must be in how the headers or content is added to the form.


I just don't see what I am doing wrong.

0 Votes 0 ·

Maybe you can look at the header and content settings in this post:
How to upload file to server with HTTP POST multipart/form-data?

0 Votes 0 ·