How to upload image on server in asp.net core?

asp.net-core asp.net-core-webapi c# entity-framework-core

Question

My task is to create a model and database for web API and CRUD purposes, one of the model properties is the photo of a car. While hardcoding data for database migration, how to set that property as a photo and save a photo path to SQL database. Later I have to manipulate with the Postman to make CRUD and API manipulations with that photo and also the other properties of that car. What is the easiest solution? I have found some info about IFormFile and byte but not sure how to do that correctly. I am using asp.net core 2.2. Thank you!

1
0
5/20/2019 7:45:48 PM

Accepted Answer

You could try to follow steps below :

1.Add a new folder to the project and call it wwwroot , and create images folder and Cars subfolder in wwwroot folder.

2.Model

public class Car
{
    public int Id { get; set; }
    public string CarName { get; set; }
    public string ImagePath { get; set; }
}
public class CarViewModel
{
    public string CarName { get; set; }
    public IFormFile Image { get; set; }
}

3.Controller

 [Route("api/[controller]")]
[ApiController]
public class CarsController : ControllerBase
{
    private readonly IHostingEnvironment _hostingEnv;
    private readonly WebAPIDbContext _context;

    public CarsController(WebAPIDbContext context, IHostingEnvironment hostingEnv)
    {
        _hostingEnv = hostingEnv;
        _context = context;
    }

    [HttpPost]
    public async Task<ActionResult> Post([FromForm] CarViewModel carVM)
    {
        if (carVM.Image != null)
        {
            var a = _hostingEnv.WebRootPath;
            var fileName = Path.GetFileName(carVM.Image.FileName);
            var filePath = Path.Combine(_hostingEnv.WebRootPath, "images\\Cars", fileName);

            using (var fileSteam = new FileStream(filePath, FileMode.Create))
            {
                await carVM.Image.CopyToAsync(fileSteam);
            }

            Car car = new Car();
            car.CarName = carVM.CarName;
            car.ImagePath = filePath;  //save the filePath to database ImagePath field.
            _context.Add(car);
            await _context.SaveChangesAsync();
            return Ok();
        }
        else
        {
            return BadRequest();
        }
    }
}
1
5/21/2019 6:11:49 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow