Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP Core WebApi Test File Upload using Postman

I have created an endpoint that takes an arbitrary file:

[HttpPost()]
public async Task<IActionResult> CreateFile(IFormFile file)

When I test it with Postman, the file is always null.

Here is what I am doing in Postman:

Postman screenshot

What am I doing wrong?

like image 368
Zeus82 Avatar asked Oct 23 '17 17:10

Zeus82


People also ask

How do I send a file using Postman?

Firstly, make a postman echo request and delete the body contents. After that, construct a form data body to see the file as it's being uploaded. Then, click on “body” and select form-data as the body type. Next, assign a key to the file value so it reflects to “select files”.


3 Answers

Thanks to @rmjoia's comment I got it working! Here is what I had to do in Postman:

enter image description here

like image 110
Zeus82 Avatar answered Sep 28 '22 04:09

Zeus82


The complete solution for uploading file or files is shown below:

  • This action use for uploading multiple files:

    // Of course this action exist in microsoft docs and you can read it. HttpPost("UploadMultipleFiles")] public async Task<IActionResult> Post(List<IFormFile> files) {      long size = files.Sum(f => f.Length);      // Full path to file in temp location     var filePath = Path.GetTempFileName();      foreach (var formFile in files)     {         if (formFile.Length > 0)             using (var stream = new FileStream(filePath, FileMode.Create))                 await formFile.CopyToAsync(stream);     }      // Process uploaded files      return Ok(new { count = files.Count, path = filePath}); } 

The postman picture shows how you can send files to this endpoint for uploading multiple files: enter image description here

  • This action use for uploading single file:

    [HttpPost("UploadSingleFile")] public async Task<IActionResult> Post(IFormFile file) {      // Full path to file in temp location     var filePath = Path.GetTempFileName();      if (file.Length > 0)         using (var stream = new FileStream(filePath, FileMode.Create))             await file.CopyToAsync(stream);      // Process uploaded files      return Ok(new { count = 1, path = filePath}); } 

The postman picture shows how you can send a file to this endpoint for uploading single file: enter image description here

like image 38
SLDev Avatar answered Sep 28 '22 03:09

SLDev


Your should be like that

 [HttpPost]       
   public async Task<IActionResult> UploadFile([FromForm]UploadFile updateTenantRequest)
        {
}

Your class should be like:-

public class UpdateTenantRequestdto
    {


        public IFormFile TenantLogo { get; set; }
    }

and then enter image description here

like image 30
MayankGaur Avatar answered Sep 28 '22 04:09

MayankGaur