Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image upload in .NET Core Web API

I'm developing a Web API with .Net Core, where I need to allow a client to upload a list of files (mostly images) and save them to the server.

Im using ASP.NET Core 3.0

This is my startup file Startup.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Http;


namespace ImageUplaodDemo
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

This is my ImageController file ImageController.cs:

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace ImageUploadDemo.Controllers
{
    [Route("api/[controller]")]
    public class ImageController : ControllerBase
    {
        public static IHostingEnvironment _environment;
        public ImageController(IHostingEnvironment environment)
        {
            _environment = environment;
        }
        public class FIleUploadAPI
        {
            public IFormFile files { get; set; }
        }
        [HttpPost]
        public async Task<string> Post(FIleUploadAPI files)
        {
            if (files.files.Length > 0)
            {
                try
                {
                    if (!Directory.Exists(_environment.WebRootPath + "\\uploads\\"))
                    {
                        Directory.CreateDirectory(_environment.WebRootPath + "\\uploads\\");
                    }
                    using (FileStream filestream = System.IO.File.Create(_environment.WebRootPath + "\\uploads\\" + files.files.FileName))
                    {
                        files.files.CopyTo(filestream);
                        filestream.Flush();
                        return "\\uploads\\" + files.files.FileName;
                    }
                }
                catch (Exception ex)
                {
                    return ex.ToString();
                }
            }
            else
            {
                return "Unsuccessful";
            }
        }
    }
}

Im trying to upload a image using POSTMAN by POST operation. I assigned REQUEST to POST and im using form-data under Body tag and assigned KEY as file to upload a file from the desktop. But im getting the following error.

I have tried all possible but been getting the same error...

Check through the code once and there any modification need to be done on the code or any modifications on postman....

{
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.13",
    "title": "Unsupported Media Type",
    "status": 415,
    "detail": null,
    "instance": null,
    "extensions": {
        "traceId": "|2c45b532-43521b159e7b734f."
    }
}
like image 599
User8686 Avatar asked Sep 12 '19 11:09

User8686


2 Answers

[HttpPost("UploadFile")]
 public async Task<string> UploadFile([FromForm] IFormFile file)
    {
        string fName = file.FileName;
        string path = Path.Combine(hostingEnvironment.ContentRootPath, "Images/" + file.FileName);
        using (var stream = new FileStream(path, FileMode.Create))
        {
            await file.CopyToAsync(stream);
        }
        return file.FileName; 
    }

You can use this in your controller class. Don't need to create a FileUploadAPi class.

like image 152
Kushan Hansika Avatar answered Oct 04 '22 02:10

Kushan Hansika


Remove these lines:

app.Run(async (context) =>
{
    await context.Response.WriteAsync("Controller didn't find anything!");
});

You're short-circuiting every request and just returning "Controller didn't find anything!" with that. Nothing ever even makes it into the pipeline.

like image 21
Chris Pratt Avatar answered Oct 04 '22 03:10

Chris Pratt