I'm currently developing a REST web service using Web API.
Now I am trying to receive stream file and object through the post.
When I sent it without the JobPosition object I received the file correctly, also when I sent the JobPosition without the file I received the JobPosition correctly.
But when I sent the stream file and the object through the postman I receive the error.
I would appreciate your help to understand if this is possible, and if so, the direction that will help me.
public class JobPosition
{
public int Id { set; get; }
public string Title { set; get; }
}
[HttpPost]
[Route("Job")]
public async Task<bool> Post(JobPosition job)
{
var multipartMemoryStreamProvider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(multipartMemoryStreamProvider, new CancellationToken());
var stream = await multipartMemoryStreamProvider.Contents[0].ReadAsStreamAsync();
// implementaion
return true;
}
Postman request:
I tried all the possible combinations with the Content-Type with no success.
Remove the (JobPosition job)
action function parameter, and instead read that with your own code via the multipartMemoryStreamProvider
object.
await multipartMemoryStreamProvider.Contents[0].ReadAsStreamAsync(); //Stream
await multipartMemoryStreamProvider.Contents[1].ReadAsStreamAsync(); //JSON
Something like that. The order will be important. It's best if you instead assume it could come in any order, loop over the Contents collection, and handle according to the name of the variable.
Maybe you can use the FormData provided by the MultipartFormDataStreamProvider to extract the JobPosition.
public async Task<IHttpActionResult> PostUploadFile()
{
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
try
{
// Read the form data.
await Request.Content.ReadAsMultipartAsync(provider);
NameValueCollection formdata = provider.FormData;
JobPosition jobPosition = new JobPosition()
{
Id = formdata["Id"],
Title = bool.Parse(formdata["Title"])
};
foreach (MultipartFileData file in provider.FileData)
{
var fileName = file.Headers.ContentDisposition.FileName.Replace("\"", string.Empty);
byte[] documentData = File.ReadAllBytes(file.LocalFileName);
/// Save document documentData to DB or where ever
/// --- TODO
}
return Ok(jobPosition);
}
catch (System.Exception e)
{
return BadRequest(e.Message);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With