Search code examples
.net-coreasp.net-core-webapiinsomnia

Problem with uploading file .NET Core Web API


I'm trying to upload file (just .jpeg image) and save it on my server. I've written the following code for this:

Db context

public class ApplicationContext : DbContext
{
    private readonly string _connectionString;

    public ApplicationContext(IConfiguration configuration)
    {
        _connectionString = configuration.GetConnectionString("Recipes");
    }

    public DbSet<FileModel> Files { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseNpgsql(_connectionString);
    }
}

Model

public class FileModel
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public string Name { get; set; }
    public string Path { get; set; }
}

Method of my controller for uploading

   public async Task<IActionResult> AddFile(IFormFile uploadedFile)
    {
        string path = "";

        if (uploadedFile != null)
        {
            // путь к папке Files
            path = "/Files/" + uploadedFile.FileName;

            using (var fileStream = new FileStream(_appEnvironment.WebRootPath + path, FileMode.Create))
            {
                await uploadedFile.CopyToAsync(fileStream);
            }

            FileModel file = new FileModel { Name = uploadedFile.FileName, Path = path };
            _applicationContext.Files.Add(file);
            _applicationContext.SaveChanges();
        }

The the next step that I'm going to do is testing it with the help of Insomnia rest client. I had setted up all acording to Insomnia documentation (to passing multipart/form-data header) and sent request. But in the uploadedFile I see null.

Here is screenshot of Insomnia enter image description here

And screen of the result: enter image description here

Why uploadedFile is null? Where is the mistake?


Solution

  • Parameter name in your client is image not expected uploadedFile defined in Controller action