【发布时间】:2018-12-16 20:57:20
【问题描述】:
我很难上传图片然后在我的视图中显示它。我在这里浏览了很多帖子,出于某种原因,没有什么对我真正有用。
图片已上传(在我的情况下保存在~/Content/Images,但未显示在视图中。整个项目已在 Azure 上发布。
请从验证上传文件是否真的是图片或处理图片大小等事情中抽象出来。
我的领域模型是:
public class Product
{
...
public string ProductImageUrl { get; set; }
...
}
控制器 - 发布方法:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(/*[Bind(Include = "ProductId,ProductName,ProductDescription,ProductPrice, CategoryId, Quantity, picture")]*/ Product product, HttpPostedFileBase picture)
{
if (ModelState.IsValid)
{
db.Products.Add(product);
if (picture != null)
{
var originalFileName = Path.GetFileName(picture.FileName);
string fileId = Guid.NewGuid().ToString().Replace("-", "");
var path = Path.Combine(Server.MapPath("~/Content/Images/"), fileId + ".jpg");
picture.SaveAs(path);
product.ProductImageUrl = path;
product.ProductImageName = fileId;
db.SaveChanges();
}
db.SaveChanges();
return RedirectToAction("Index");
}
return View(product);
}
我的看法是:
@foreach (var item in Model)
{
<tr>
<td>
<img src="@item.ProductImageUrl" />
</td>
...
【问题讨论】:
-
您需要在带有 guid 的文件名中提供 .jpg 或 .png 等图像类型并将其保存在 ProductImageUrl 中
-
我试过了,但是没用
-
您能否在开发者工具的网络选项卡中检查此图像的请求。这很可能会告诉您为什么它没有显示。
-
@xcelm
item.ProductImageUrl生成的字符串是什么? -
@Valkyrie - product.ProductImageUrl = path;
标签: c# html asp.net-mvc entity-framework