Hello friends, today we will solve a little problem which a few people might encounter while building APIs in ASP.net core. This will be a very short post, since we will go straight to the point with the solution. We will see how to in ASP.net core upload files and json data for each file

Why ?

You might come across a situation where you need to build an API to upload multiple files, and allow the users of the API to pass additional information associated to each of those files to your API. This post tells exactly how to do that.

How ?

To upload a single file, it is quite easy. To upload multiple files too. Now we want to upload files and json data for each file. To do that, follow these steps.

  • First, define the information you want to associate to each file uploaded via your API. In our case, this will be the attributes corresponding to each.
  • Second, define a model binder which will be in charge of binding the json data (we send associated to the files we upload) to the list of C# objects passed to the controller’s action.
  • Create the controller method which will be in charge of uploading the files and and their information. Notice that we add the [FromForm] attribute to our list of file attributes.
  • Upload the files and the json data: To do this, you will create a post request with a form. The key in the form which takes the file information will be named fileAttributes as what you can see above. Then, here is an example of json data sent alongside the files we upload.

If you like this post, don’t hesitate to follow me on Twitter or Github and subscribe to this page’s notifications to stay updated with new articles or like my page on Facebook.

Conclusion

With this, you will be able to send files to your API and add information to them by simply passing an array of json data. This solution targets a small problem, but might be useful to a large number of people.

References

https://stackoverflow.com/questions/41367602/upload-files-and-json-in-asp-net-core-web-api

ASP.net Core Upload Files and Json Data For each file.

Follow me on social media and stay updated

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.