uploading an image api in asp.net core

Viewed 92

I'm building an api to store an image as part of the machine model class to consuming it in the xamarin.forms so this is the machine class:

 public class Machine
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public string Machine_Qr { get; set; }
        public string Machine_Name { get; set; }
        [NotMapped]
        public string Image { get; set; }
}

and this is the machine controller:

public class MachineController : ControllerBase
    {
        private readonly DataContext _context;
        private IHostingEnvironment _hostingEnvironment;

        public MachineController(DataContext context, IHostingEnvironment environment)
        {
            _context = context;
            _hostingEnvironment = environment ?? throw new ArgumentNullException(nameof(environment));



        }
        [HttpPost]
        public async Task<ActionResult<Machine>> Create(Machine machine)
        {
            if (ModelState.IsValid)
            {
                var files = HttpContext.Request.Form.Files;
                foreach (var Image in files)
                {
                    if (Image != null && Image.Length > 0)
                    {

                        var file = Image;
                        var uploads = Path.Combine(_hostingEnvironment.WebRootPath, "uploads\\img\\Machines");

                        if (file.Length > 0)
                        {
                            var fileName = ContentDispositionHeaderValue.Parse
                                (file.ContentDisposition).FileName.Trim('"');

                            System.Console.WriteLine(fileName);
                            using (var fileStream = new FileStream(Path.Combine(uploads, file.FileName), FileMode.Create))
                            {
                                await file.CopyToAsync(fileStream);
                                machine.Image = file.FileName;
                            }


                        }
                    }
                }

                _context.Add(machine);
                await _context.SaveChangesAsync();

            }
            return CreatedAtAction(nameof(PostMachine), new { id = machine.Machine_Qr }, machine);
        }

But when I'm trying to test the api in swagger I got this message:

System.InvalidOperationException: Incorrect Content-Type: application/json
   at Microsoft.AspNetCore.Http.Features.FormFeature.ReadForm()
   at Microsoft.AspNetCore.Http.DefaultHttpRequest.get_Form()
   at WebApi.Controllers.MachineController.Create(Machine machine) in C:\Users\amyra\source\repos\WebApi\Controllers\MachineController.cs:line 35

The machineController line 35 is :

 var files = HttpContext.Request.Form.Files;
1 Answers

You should receive the Image as IFormFile property in your Machine class

[NotMapped]
public IFormFile Image { get; set; }

And then use [FromForm] attribute in your request

[HttpPost]
public async Task<ActionResult<Machine>> Create([FromForm] Machine machine)

Now you can remove these lines

var files = HttpContext.Request.Form.Files;
                foreach (var Image in files)
                {
                    
                }

And directly use machine.Image that you uploaded through Swagger

var file = machine.Image;
if (file != null && file.Length > 0)
{
    var fileName = ContentDispositionHeaderValue.Parse
                                
    (file.ContentDisposition).FileName.Trim('"');

    System.Console.WriteLine(fileName);
    using (var fileStream = new FileStream(Path.Combine(uploads, file.FileName), FileMode.Create))
        {
             await file.CopyToAsync(fileStream);
        }
}
Related