[英]Add a picture in a dotnet core model
I have a dotnet core (+razor +ef) application with the usual model of a Product
:-) 我有一个dotnet core(+ razor + ef)应用程序,该
Product
具有通常的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
. 产品应具有关联的图片,该图片从
Products\\Create.cshtml
和Products\\Edit.cshtml
页面上载,存储在数据库表中,并显示在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? 第一个问题:对图片使用
byte[]
是否正确?
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? 第二个问题:由于我想我无法自动为图片添加CRUD页面,因此如何从剃须刀
Create.cshtml
页面上载图片?
Thanks a lot 非常感谢
In your View
you can 在您的
View
您可以
1) Either go with embedded image bytes: 1)要么嵌入图像字节:
<img src="data:image/jpeg;base64,@Convert.ToBase64String(Model.Image)" />
2) Or - use the separate controller action like GetImage
below, which returns the file: 2)或-使用单独的控制器操作,例如下面的
GetImage
,它返回文件:
<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. 注意:如果图像不是太大,则可以将它们存储在DB中。 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.
但这肯定是另外一个故事。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.