How can I send file to list - .net core web api - postman

Viewed 4027

I'm trying to send a file from a postman to a web api, method on web api is expecting a list of type which contains doc type, file and folder name.. posted below:

Web api method:

[HttpPost("post-images")]
public async Task<IList<RepositoryItem>> PostAnImages (IList<PostRepoRequest> request)
{
    // rest of the code 
}

PostRepoRequest class:

public class PostRepoRequest
{
    public FileType FileType { get; set; }
    public IFormFile File { get; set; }
    public string Folder { get; set; }
}

As it's possible to notice I've never received a file, its allways null, I've tried also setting a header content-type as multipart/form-data but that didn't worked aswell..

What might be the trick here?

Thanks

Cheers

3 Answers

You need to change the request body with dot pattern like this:

enter image description here

Then you need to add [FromForm] attribute to the controller input parameter. Also note that the variable names in the postman and controller must match.

[HttpPost("post-images")]
public async Task<IList<RepositoryItem>> PostAnImages ([FromForm]IList<PostRepoRequest> repositoryItems)

With these changes, you will be able to get the request correctly:

enter image description here

Try to send file as separated parameter

[HttpPost("post-images")]
public async Task<IList<RepositoryItem>> PostAnImages (IList<PostRepoRequest> request, [FromForm]List<IFormFile> files)
{
    // rest of the code 
}

and in client (assuming that can be Angular):

let input = new FormData();
for (var i = 0; i < this.filesToUpload.length; i++) {
   input.append("files", this.filesToUpload[i]);
}

There is an invisible selectbox, just move your cursor to left and you'll see the selectable area. Then select it as a file.

enter image description here

And add [FromBody] at he beginnig of ypur method parameter like ([FromBody]IList<PostRepoRequest> request)

And last, update the Key to ...[0][file] (you've forgot [])

Related