简体   繁体   English

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

[英]Uploading and displaying image in ASP.NET MVC

I have hard time uploading picture and then displaying it in my view. 我很难上传图片,然后在视图中显示它。 I went through a lot of posts here and for some reason nothing really works for me. 我在这里浏览了很多帖子,由于某种原因,没有任何东西真正适合我。

Picture gets uploaded (in my case saved in ~/Content/Images , but is not displayed in the view. Whole project is published on Azure. 图片被上传(在我的情况下保存为~/Content/Images ,但未在视图中显示。整个项目都在Azure上发布。

Please abstract from things like verifying if the uploaded file is really a picture or handling the size of the picture. 请从诸如验证上传的文件是否真的是图片或处理图片的大小之类的内容中抽象出来。

My domain model is: 我的域模型是:

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

Controller - post method: 控制器-发布方法:

[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);
} 

My view is: 我的看法是:

       @foreach (var item in Model)
        {
            <tr>
                <td>
                    <img src="@item.ProductImageUrl" />
                </td>
...

Problem is that your are storing absolute path in the ProductImageUrl field and that's why its not working in your hosting environment. 问题是您将绝对路径存储在ProductImageUrl字段中,这就是为什么它在您的托管环境中不起作用的原因。 More importantly you don't need both ProductImageUrl and ProductImageName to handle images. 更重要的是,您不需要ProductImageUrlProductImageName来处理图像。 Use only ProductImageName . 仅使用ProductImageName

Do as follows: 进行如下操作:

Your Product model should as follows: 您的Product型号应如下:

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

Then in the Controller method: 然后在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);
} 

Then in the View as follows: 然后在View中如下所示:

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

Hope it will work for you! 希望它对您有用! Thank you. 谢谢。

I would add a <base> tag to your view so that all links are relative to your site. 我会在您的视图中添加一个<base>标记,以便所有链接都相对于您的站点。 Then you don't need to build a path to the image at all. 然后,您根本不需要构建图像的路径。

For intance, if you site is at https://bestsiteever.com your tag would look like this: 例如,如果您的网站位于https://bestsiteever.com ,则您的标签应如下所示:

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

and your path would be: 您的路径将是:

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

If you post your image as a byte array, you should be able to turn it in Base64 format and display in view : 如果将图像发布为字节数组,则应该能够将其转换为Base64格式并在view中显示:

<img src="data:image;base64,@Convert.ToBase64String(item.ProductImageUrl)" />

Worth a shot. 值得一试。

Correct me if i'm wrong but the string stored in item.ProductImageUrl is a path like c:\\\\.. right? 如果我错了,请纠正我,但是存储在item.ProductImageUrl的字符串是一个类似于c:\\\\..的路径c:\\\\..对吗?

Server.MapPath gives relative hard drive location on the server. Server.MapPath给出服务器上相对硬盘驱动器的位置。 If you put that location in src then you are asking the browser to find that file in your LOCAL hard drive. 如果将该位置放在src中,则要求浏览器在本地硬盘中找到该文件。

Try item.ProductImageUrl = "<url to your site>/Content/Images/" + fileId + ".jpg"; 尝试item.ProductImageUrl = "<url to your site>/Content/Images/" + fileId + ".jpg"; .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM