如何在asp.net core的服务器上上传图像?

Iva*_*van 1 c# entity-framework-core asp.net-core asp.net-core-webapi

我的任务是为 Web API 和 CRUD 目的创建模型和数据库,模型属性之一是汽车的照片。在为数据库迁移硬编码数据时,如何将该属性设置为照片并将照片路径保存到 SQL 数据库。后来我必须使用 Postman 进行操作,以使用该照片以及该车的其他属性进行 CRUD 和 API 操作。什么是最简单的解决方案?我找到了一些关于 IFormFile 和 byte 的信息,但不确定如何正确地做到这一点。我正在使用 asp.net 核心 2.2。谢谢!

Xue*_*hen 6

您可以尝试按照以下步骤操作:

1.在项目中添加一个新文件夹并命名为wwwroot,并在wwwroot文件夹中创建images文件夹和Cars子文件夹。

2.型号

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; }
}
Run Code Online (Sandbox Code Playgroud)

3.控制器

 [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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)