Reputation: 2552
I have a dotnet core (+razor +ef) application with the usual model of a Product
:-)
A product should have a picture associated, uploaded from the Products\Create.cshtml
and Products\Edit.cshtml
pages, stored in a table of the DB, and showed in the Products\Details.cshtml
.
My model is something like this:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public byte[] Image { get; set; }
}
First question: is it correct the use of byte[]
for the picture?
Second question: since I guess I cannot automatically scaffolding the CRUD pages for a picture, how can I upload the image from the razor Create.cshtml
page?
Thanks a lot
Upvotes: 1
Views: 558
Reputation: 28290
In your View
you can
1) Either go with embedded image bytes:
<img src="data:image/jpeg;base64,@Convert.ToBase64String(Model.Image)" />
2) Or - use the separate controller action like GetImage
below, which returns the file:
<img src="@Url.Action("GetImage", new { productId = Model.Id })" />
In this case you will need an additional controller action like this:
[HttpGet]
public FileStreamResult GetImage(Guid productId)
{
using (var dbContext = new DbContext())
{
var product = dbContext.Product.FirstOrDefault(x => x.Id == productId);
var ms = new MemoryStream(product.Image);
return new FileStreamResult(ms, "image/jpeg");
}
}
NOTE: if the images are not too big, storing them in DB might be OK. If not - I would suggest to consider storing them on file system (or in cloud storage) with metadata (like file name, etc.) in your database. But that is a different story for sure.
Upvotes: 2