0

I have a asp web api Post method in controller with model that can handle json object and files together

This is the POST method:

public async Task<IHttpActionResult> PostAsync([Required]Models.Email email, CancellationToken token = default(CancellationToken))
{
if (multipartContentProvider.IsMultipartRequest)
//manages the file upload..
}

return Content(HttpStatusCode.Created, "uploaded");
}

and here is the javascript:

var formdata = new FormData();
//the file
formData.append('userpic', myFileInput.files[0], 'chris.jpg');

the json object
formData.append('email', new Blob([JSON.stringify({
    subject: "hello there",
    description: "this is a text"
})], {
    type: "application/json"
}));


fetch(url, {
            method: 'POST',
            body: formData,
            headers: {

            }
        }).then(function (response) {
            if (response.status === 404) {
                console.log("that did not work :(");
                return;
            }
            return response.json();
        }).then(function (data) {...}

In the middleware that handles the multipart request I see tvo items in the stream, the json object itself with content-type: application/json and I see the file with content-type = application/octet-stream.

But it always crashes with modelstate error, saying that:

{"message":"The request is invalid.","modelState":{"email":["The email field is required."]}}

How can I upload to request object to the controller and have it recognize that one of the item is the datamodel "email" ?

aghaux
  • 729
  • 4
  • 14
  • 38
  • I think you need to `JSON.stringify(formData)` in it's entirety. Very possible the controller is not able to parse the formData because it's not a valid JSON object. – Iskandar Reza Jan 24 '19 at 23:20
  • Oops sorry I did a little further reading and while I still think that's the part that is the issue, it appears that there's a way to post formData properly: https://stackoverflow.com/questions/46640024/how-do-i-post-form-data-with-fetch-api – Iskandar Reza Jan 24 '19 at 23:23

0 Answers0