question

ADeBok-2727 avatar image
1 Vote"
ADeBok-2727 asked J4cuza-0641 answered

Generating form data for an API request

Hi I am trying to write a C# client for this API: https://www.directdebit.co.za/api/dos.svc

On their endpoint for "/batch/eft/" they want me to send them a file with the formData Paramater Type. As far as I understand I should be using the MultipartContent class to do this. I've managed to read the file into a string variable, I just need to assign that to a multipart/formData paramater somehow. Here's my code so far:

     // Upload a file to Direct Debit via the API
     public async void UploadFile(string filePath)
     {
         if (!File.Exists(filePath))
         {
             throw new ArgumentException($"{filePath} does not exist");
         }

         var sb = new StringWriter();
         using (var fs = File.OpenRead(filePath))
         {
             var b = new byte[1024];
             while (fs.Read(b, 0, b.Length) > 0)
             {
                 sb.Write(b);
             }
         }

         var content = sb.ToString();

         var hc = GenerateHttpClient();
         var postBody = new MultipartContent();
            
         // I am a little confused. What do I do now?
            
         var resp = await hc.PostAsync(url + "/batch/eft", postBody);
         resp.EnsureSuccessStatusCode();
     }

Thanks in advance.
Arie

dotnet-csharp
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.

ADeBok-2727 avatar image
1 Vote"
ADeBok-2727 answered

I figured it out. I should have used MultipartFormDataContent, instead of just MultipartContent. The correct code is then:

         var postBody = new MultipartFormDataContent
         {
             {new ByteArrayContent(content.ToArray()), "file_data", Path.GetFileName(filePath)}
         };

         var resp = await hc.PostAsync(_url + "/batch/eft", postBody);
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.

J4cuza-0641 avatar image
0 Votes"
J4cuza-0641 answered

Thanks for posting the answer, I was also struggling with sending a file.

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.