How to upload a file with Content Type multipart/form-data to an endpoint using a VB.NET code inside UiPath Studio?

How to upload a file with Content-Type multipart/form-data to an endpoint using a Vb.Net code inside UiPath Studio?

Issue description

A RestAPI sample works in Postman for uploading a file with Content-Type multipart/form-data, but does not have the same results while trying multiple configurations in HTTP Request activity from the UiPath.WebAPI.Activities package in UiPath Studio.


Example from Postman:

image.png
image.png



Resolution

The following scenario presents a custom VB.NET code approach with RestSharp library within an Invoke Code activity for a Studio 23.10.7 Windows project with VB language support.

  1. Delete/remove the UiPath.WebAPI.Activities package from project (if it was installed previously) and install and use the RestSharp.111.3.0 library (or a lower version of RestSharp library in case the same library is used as a sub-dependency in another project package).

  1. In the Imports panel add RestSharp and RestSharp.Extensions

  1. Add in Invoke Code activity for VB.Net

Note: Adjust the provided sample code based on specific needs.

Dim expires = expires_value
Dim signature = signature_value
Dim file_path = file_to_upload_path
Dim options As New RestClientOptions(main_url_address)
Dim client As New RestClient(options)
Dim request As New RestRequest($"/v2/documents?Expires={expires}&Signature={signature}", Method.Post)
request.AddHeader("Authorization", access_token)
request.AlwaysMultipartFormData = True
If File.Exists(file_to_upload_path) Then
   request.AddFile("FileToPlay.txt",file_to_upload_path,"text/plain")
Else
   Console.WriteLine($"File {file_path} not found")
End If
request.AddParameter("data", data_value)
Dim response As RestResponse = client.ExecuteAsync(request).Result
Console.WriteLine(response.StatusCode)
Console.WriteLine(response.Content)

In Edit arguments add the values used as inputs in the code (the values of the input arguments can be declared in Assign activities).

Example:
image.png

data_value sample value

 "{""description"":""Requestor is XXXX"", ""referenceId"":72731, ""referenceType"":""journals"", ""uploadOriginatedService"":""services.journals""}"

In the end, if everything was set correctly, the file should be uploaded successfully: