HttpClient MultiPart form file upload

danilos 101 Reputation points
2021-05-21T18:55:08.593+00:00

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

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,417 questions
{count} votes

Accepted answer
  1. danilos 101 Reputation points
    2021-05-26T07:39:28.213+00:00

    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

    1 person found this answer helpful.
    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Timon Yang-MSFT 9,576 Reputation points
    2021-05-24T08:06:19.02+00:00

    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. Karen Payne MVP 35,201 Reputation points
    2021-05-24T16:32:29.057+00:00

    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.