asp.net core 3.1 iformfile image code example
Example 1: save image IFOrmFile to path in asp.net 5 C# web api
[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;
_context.Add(car);
await _context.SaveChangesAsync();
return Ok();
}
else
{
return BadRequest();
}
}
}
Example 2: save image IFOrmFile to path in asp.net 5 C# web api
using Microsoft.AspNetCore.Hosting;
public class ImageController : Controller
{
private readonly IWebHostEnvironment _hostEnvironment;
public ImageController(..., IWebHostEnvironment hostEnvironment)
{
...
this._hostEnvironment = hostEnvironment;
}
...
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("ImageId,Title,ImageFile")] ImageModel imageModel)
{
if (ModelState.IsValid)
{
string wwwRootPath = _hostEnvironment.WebRootPath;
string fileName = Path.GetFileNameWithoutExtension(imageModel.ImageFile.FileName);
string extension = Path.GetExtension(imageModel.ImageFile.FileName);
imageModel.ImageName=fileName = fileName + DateTime.Now.ToString("yymmssfff") + extension;
string path = Path.Combine(wwwRootPath + "/Image/", fileName);
using (var fileStream = new FileStream(path,FileMode.Create))
{
await imageModel.ImageFile.CopyToAsync(fileStream);
}
_context.Add(imageModel);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(imageModel);
}
....
}