Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to receive stream and object through post request in Web API?

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: enter image description here enter image description here

I tried all the possible combinations with the Content-Type with no success.

like image 205
Jenia Finkler Avatar asked Feb 16 '18 10:02

Jenia Finkler


2 Answers

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.

like image 61
Kind Contributor Avatar answered Sep 25 '22 15:09

Kind Contributor


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);
        }
    }
like image 30
Gert Botha Avatar answered Sep 22 '22 15:09

Gert Botha