[英]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. 我的任务是为Web API和CRUD创建模型和数据库,其中一个模型属性是汽车的照片。 While hardcoding data for database migration, how to set that property as a photo and save a photo path to SQL database. 在对数据库迁移进行硬编码时,如何将该属性设置为照片并将照片路径保存到SQL数据库。 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. 后来我不得不与邮递员一起操纵使用该照片以及该汽车的其他属性进行CRUD和API操作。 What is the easiest solution? 什么是最简单的解决方案? I have found some info about IFormFile and byte but not sure how to do that correctly. 我找到了一些关于IFormFile和byte的信息但不确定如何正确地做到这一点。 I am using asp.net core 2.2. 我使用的是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. 1.在项目中添加一个新文件夹并将其命名为wwwroot
,并在wwwroot
文件夹中创建images文件夹和Cars子文件夹。
2.Model 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; }
}
3.Controller 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();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.