asp.net core upload image code example
Example 1: 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);
}
....
}
Example 2: asp net core image server
[HttpPost]
public ActionResult RetrieveImage()
{
Image img = db.Images.OrderByDescending
(i=>i.Id).SingleOrDefault();
string imageBase64Data =
Convert.ToBase64String(img.ImageData);
string imageDataURL =
string.Format("data:image/jpg;base64,{0}",
imageBase64Data);
ViewBag.ImageTitle = img.ImageTitle;
ViewBag.ImageDataUrl = imageDataURL;
return View("Index");
}