When I try to upload a file to an API with the help of RestSharp, I get the response:
'Error calling UploadFile: {"message":"The given data was invalid.","errors":{"file":["The file field is required."]}}'
When I upload the file to the API using their plattform everything works as expected. Request:
curl -X POST "https://{URL}/v1/customer/files/ef02f89c-accf-4ca5-a05a-456cf65242d3" -H "accept: application/json" -H "Content-Type: multipart/form-data" -F "[email protected];type=image/gif"
Response:
Code 200
Response body
Download
{
"id": "ef02f89c-accf-4ca5-a05a-456cf65242d3",
"fileName": "dancing-penguins.gif"
}
My code to upload the file:
private ApiResponse<File> UploadFileWithHttpInfo(File file, byte[] fileData)
{
var pathParams = new Dictionary<string, string>() { ["id"] = Configuration.ApiClient.ParameterToString(file.Id) };
var headerParams = new Dictionary<string, string>(Configuration.DefaultHeader);
string httpHeaderAccept = "application/json";
if (httpHeaderAccept != null)
headerParams.Add("Accept", httpHeaderAccept);
if (!string.IsNullOrEmpty(Configuration.AuthString))
headerParams["Authorization"] = Configuration.AuthString;
var fileParams = new Dictionary<string, FileParameter> { ["file"] = FileParameter.Create(file.FileName, fileData, file.FileName, MapContentTypeFromExtension(file.FileName)) };
string path = "/v1/customer/files/{id}";
Method method = Method.POST;
var request = new RestRequest(path, method);
foreach (var param in pathParams) request.AddParameter(param.Key, param.Value, ParameterType.UrlSegment);
foreach (var param in headerParams) request.AddHeader(param.Key, param.Value);
foreach (var param in fileParams) request.AddFile(param.Value.Name, param.Value.Writer, param.Value.FileName, param.Value.ContentLength, param.Value.ContentType);
// set user agent
//RestClient.UserAgent = Configuration.UserAgent;
request.RequestFormat = DataFormat.Json;
InterceptRequest(request);
var response = RestClient.Execute(request);
InterceptResponse(request, response);
Exception exception = ExceptionFactory(nameof(UploadFile), response);
return exception == null ? new ApiResponse<File>(Configuration, response) : throw exception;
}
Any help is appreciated.