Tom el Safadi
Tom el Safadi

Reputation: 6746

Asp.Net Web Api multiple files with additional data for each

I am trying to send multiple files along with some data for every file. This is my model:

public class FileDTO
{
    [Required]
    public IFormFile File { get; set; }
    [Required]
    public string CategoryName { get; set; }
    [Required]
    public string CategoryDescription { get; set; }
    public string Detail { get; set; }
}

This is my controller:

[HttpPost("Upload/{id:int}")]
public async Task<IActionResult> Upload(int id, IEnumerable<FileDTO> appFileDTOs)
{
    ...
}

Is this even a correct way to do so? How do I send such a request in Postman to simulate it?

Thanks in advance!

Edit

I tried it like this in Postman:

Postman Screenshot

Everything submits correctly besides the image. For some reason the image is always null...

Upvotes: 0

Views: 156

Answers (2)

itminus
itminus

Reputation: 25350

[] represents collection/dictionary index while dot(.) represents there's a property.

So you should rename all the field names with the dot representation.

For example, change

appFileDTOs[0][File]

to

appFileDTOs[0].File

Demo

enter image description here

Upvotes: 1

Ashutosh Kushawaha
Ashutosh Kushawaha

Reputation: 791

try this it may help you,

send from formData.

in model key send value as

[
{
"CategoryName":"Category1",
"CategoryDescription ":"Category1 Description",
"Detail":"Details "
},
{
"CategoryName":"Category2",
"CategoryDescription ":"Category2 Description",
"Detail":"Details2"
}

]

and for file send first file as file1 and second file as file2; enter image description here

In server side , remove IEnumerable of FileDTO appFileDTOs from method name. get value of model as

var data = JsonConvert.DeserializeObject<List<FileDTO>>(Request.Form["model"]);

simillary for file

   var fileUpload1 = Request.Form.Files["file1"];
   var fileUpload2 = Request.Form.Files["file2"];

Upvotes: 0

Related Questions