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