在ASP.NET MVC中上传和显示图像

问题描述 投票:2回答:4

我很难上传图片然后在我的视图中显示它。我在这里经历了很多帖子,由于某种原因,没有什么对我有用。

图片上传(在我的情况下保存在~/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>
...
c# html asp.net-mvc entity-framework
4个回答
2
投票

问题是你在ProductImageUrl字段中存储绝对路径,这就是为什么它不能在你的托管环境中工作。更重要的是,你不需要ProductImageUrlProductImageName来处理图像。仅使用ProductImageName

做如下:

您的Product模型应如下:

public class Product
{
    ...
    public string ProductImageName { get; set; }
    ...
}

然后在Controller方法中:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Product product, HttpPostedFileBase productImage)
{
   if (ModelState.IsValid)
   {
      if (productImage != null && productImage.ContentLength > 0)
      {
          var fileName = Guid.NewGuid().ToString().Replace("-", "") + "_" + Path.GetFileName(productImage.FileName);
          var path = Path.Combine(Server.MapPath("~/Content/Images/Product/"), fileName);

          productImage.SaveAs(path);
          product.ProductImageName = fileName;
      }

      db.Products.Add(product);
      await db.SaveChangesAsync();
      return RedirectToAction("Index");
   }

   return View(product);
} 

然后在View如下:

@foreach (var item in Model)
{
   <tr>
       <td>
           <img src="@Url.Content("~/Content/Images/Product/"[email protected])" />
       </td>
   <tr>
}

希望它对你有用!谢谢。


1
投票

我会在您的视图中添加一个<base>标记,以便所有链接都与您的网站相关。然后,您根本不需要构建图像的路径。

例如,如果您的网站位于qazxsw poi,您的标记将如下所示:

https://bestsiteever.com

你的道路将是:

<base href="https://bestsiteever.com" >

0
投票

如果将图像作为字节数组发布,则应该能够将其转换为Base64格式并在视图中显示:

$"/Content/Images/{fieldId}.jpg"

值得一试。


0
投票

纠正我,如果我错了,但存储在<img src="data:image;base64,@Convert.ToBase64String(item.ProductImageUrl)" /> 的字符串是一条像item.ProductImageUrl的路径对吗?

Server.MapPath提供服务器上的相对硬盘驱动器位置。如果您将该位置放在src中,那么您要求浏览器在LOCAL硬盘驱动器中找到该文件。

试试c:\\..

© www.soinside.com 2019 - 2024. All rights reserved.