Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload a single file in Web API

I am using this code to upload file in Web API. But my posted file is showing Null. Perhaps it is because the code is expecting multiple files in postman. I need to uplaod a single file through postman and not the list of files. I am sharing the code.

[HttpPost]
[Route("Upload")]
public async Task<IActionResult> Upload(string targetIdStr, string feedType, 
    string contentType, string dateCreated, string description, List<IFormFile> files)
like image 483
muzaffar mir Avatar asked Dec 12 '25 17:12

muzaffar mir


2 Answers

For uploading one file, you need to change Action like below:

        [HttpPost]
        [Route("Upload")]
        public async Task<IActionResult> Upload(string targetIdStr, string feedType,
  string contentType, string dateCreated, string description, IFormFile file)
        {
            return Ok();
        }

For request in PostMan, Send request with post->Set Body as form-data like below

enter image description here

like image 93
Edward Avatar answered Dec 15 '25 06:12

Edward


Ok I'll give you a real web api controller on how you can upload a single file. Class below is a working example. Just replace the constant value with a small file on your disk.

using System.IO;
using Microsoft.AspNetCore.Mvc;

namespace WebApi.Controllers
{
    [Route("api/[controller]")]
    public class UploadController : Controller
    {
        private const string FILEPATH = @"c:\temp\demo.txt";

        [HttpGet]
        public IActionResult JsonObject()
        {
            var file = new FileInfo(FILEPATH);
            return new OkObjectResult(new FileClass()
            {
                Name = file.Name,
                Content = System.IO.File.ReadAllBytes(FILEPATH)
            });
        }

        [HttpPost]
        public IActionResult Index([FromBody] FileClass file)
        {
            return new NoContentResult();
        }
    }

    public class FileClass
    {
        public string Name { get; set; }
        public byte[] Content { get; set; }
    }
}

Now in postman first launch the call to the get uri https://localhost:44382/api/upload

This will result in a json answer showing you the json you need to return in my case this was:

{
    "name": "demo.txt",
    "content": "dGVzdCBkYXRh"
}

In postman now choose the option post and in the body choose raw and paste the get result in it and launch it. When in debug you'll now see that the json object has arrived. Screenshot below shows the postman proof that it works: PostMan Example

like image 44
Samyne Avatar answered Dec 15 '25 06:12

Samyne