简体   繁体   中英

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

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!

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();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM