27

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?

3
  • 1
    have you tried with the form-data? and you should have a way to "simulate" a form too, by specifying the fields, and add the files too Commented Oct 23, 2017 at 17:50
  • And I also have the Header with the Content-Type = application/x-www-form-urlencoded Commented Oct 23, 2017 at 17:57
  • I got it working with form-data. I didn't need to add the content-type header. Commented Oct 23, 2017 at 18:17

4 Answers 4

39

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

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

I also wondering to transfer file but it helped me thanks. @Zeus82 can you explain or refer any link how to transfer file when I have other JSON parameters in request.
22

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

5 Comments

This is good. I am able to upload single file. However your example for multiple files, I continue to get the error in postman (following). Have you seen this? { "": [ "The input was not valid." ] }
In order to send multiple files I had to change my method signature to ... public async Task<IActionResult> UploadFiles(IFormFileCollection files) using List<IFormFile> files as upload multiple did not work for me.
For sending multiple files, both IFomFileCollection and List<IFormFile> should work. You should check you parameter name and Model validation, if you couldn't understand problem. monitor you request, because sometimes the request is not the same you are expecting.
+1 for David. I needed to use IFormFileCollection too. Using List didn't work for me also. I'm curious about it, List should work too I guess.
Just a comment to note that with this Postman file upload method, make sure to match the "Key" name in the form-data with the method input parameter name otherwise the file just shows up as null. For example: if the method is UploadFile(IFormFile myFile) make sure that in Postman you set the key field as "myFile".
1

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

Comments

1
   [HttpPost("UploadSingleFile"), Route("[action]")]
    public async Task<IActionResult> UploadSingleFile([FromForm(Name = "file")] IFormFile file)
    {


        // Process uploaded files

        string folderName = "Uploads";
        string webRootPath = hostingEnvironment.WebRootPath;
        string newPath = Path.Combine(webRootPath, folderName);
        if (!Directory.Exists(newPath))
        {
            Directory.CreateDirectory(newPath);
        }

        Repository.Models.File fileModel = new Repository.Models.File();
        fileModel.Name = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
        fileModel.Path = $"{folderName}/{file.FileName}";
        fileModel.Size = file.Length;
        fileModel.Type = file.ContentType;

        string fullPath = Path.Combine(newPath, fileModel.Name);

        fileModel.Extension = Path.GetExtension(fullPath);
        fileModel.CreatedDate = Utility.Common.GetDate;
        fileModel.CreatedBy = 1;

        //fileModel save to db

        using (var stream = new FileStream(fullPath, FileMode.Create))
        {
            //file.CopyTo(stream);
            await file.CopyToAsync(stream);
        }

        return Ok(new { count = 1, path = filePath });
    }

1 Comment

Welcome to Stack Overflow! Please don't answer just with source code. Try to provide a nice description about how your solution works. See: How do I write a good answer?. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.