Professional Documents
Culture Documents
Data For Each File - Cool Coders: Quicktips
Data For Each File - Cool Coders: Quicktips
Data For Each File - Cool Coders: Quicktips
doumer.me
31 Jul
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 ?
1 of 3 11/28/2020, 4:11 PM
ASP.net Core Upload Files and Json Data for Each file - Cool Coders about:reader?url=https://doumer.me/asp-net-core-upload-files-and-json...
2 {
4 {
5 if (bindingContext == null)
6 {
8 }
9 var valueProviderResult =
10 bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
11 if (valueProviderResult != ValueProviderResult.None)
{
12
13 bindingContext.ModelState.SetModelValue(bindingContext.ModelName
valueProviderResult);
14
var stringValue = valueProviderResult.FirstValue;
15
var result =
16
Newtonsoft.Json.JsonConvert.DeserializeObject(stringValue,
17 bindingContext.ModelType);
18 if (result != null)
19 {
20 bindingContext.Result = ModelBindingResult.Success(result);
21 return Task.CompletedTask;
22 }
23 }
24 return Task.CompletedTask;
25 }
26
2 of 3 11/28/2020, 4:11 PM
ASP.net Core Upload Files and Json Data for Each file - Cool Coders about:reader?url=https://doumer.me/asp-net-core-upload-files-and-json...
27 }
[FromForm][ModelBinder(BinderType =
typeof(FormDataJsonModelBinder))] IList<MyFileAttributes>
fileAttributes,
IList<IFormFile> files)
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.
[{ "XAxis " : 70, "YAxis" : 347}, { "XAxis " : 10, "YAxis" : 200}]
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.
3 of 3 11/28/2020, 4:11 PM