WebImage帮助器没有创建正确的图像路径?

时间:2015-03-06 11:01:57

标签: c# asp.net-mvc razor

我的问题是使用以下代码。我已经构建了WebPages应用程序,其中这一块代码完美运行,但是,在我的MVC5应用程序中,它只复制从我的PC到MSSQL数据库的本地路径,甚至没有GUID。这段代码是:

控制器:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include="productId,categoryId,brandId,Name,Price,ProductImg")] Product product)
{
    if (ModelState.IsValid)
    {
        WebImage photo = null;
        var newFileName = "";
        var imagePath = "";
        //RIJEŠITI NESTED IF
        //zašto ne prihvaća HttpPostedFileBase tip??
        photo = WebImage.GetImageFromRequest();

        if (photo != null)
        {
            newFileName = Guid.NewGuid().ToString() + "_" +
                Path.GetFileName(photo.FileName);
            imagePath = @"Content\Images\" + newFileName;

            photo.Save(@"~\" + imagePath);

            product.ProductImg = @"~\" + imagePath;
        }

        try
        {
            db.Entry(product).State = System.Data.Entity.EntityState.Modified;
            db.SaveChanges();
        }
        catch (DbUpdateConcurrencyException)
        {
            var objContext = ((IObjectContextAdapter)db).ObjectContext;

            objContext.Refresh(System.Data.Entity.Core.Objects.RefreshMode.ClientWins, product);
        }
        return RedirectToAction("Index");
    }
}

MODEL:

public class Product
{
    [ScaffoldColumn(false)]
    public int productId { get; set; }

    [DisplayName("Category")]
    public int categoryId { get; set; }

    [DisplayName("Brand")]
    public int brandId { get; set; }

    [DisplayName("Product Name")]
    [Required(ErrorMessage = "Product Name is mandatory")]
    [StringLength(160)]
    public string Name { get; set; }

    [Required(ErrorMessage = "Price is required")]
    [Range(0.01, 7000.00,
        ErrorMessage = "Price must be between 0.01 and 7000.00")]
    public decimal Price { get; set; }

    [DisplayName("Product Image")]
    [StringLength(1024)]        
    public string ProductImg { get; set; }

    public virtual Category Category { get; set; }
    public virtual Brand Brand { get; set; }
    public virtual List<OrderDetail> OrderDetails { get; set; }
}

如果用户不想更改图像,如何防止此代码向数据库写入NULL?

1 个答案:

答案 0 :(得分:0)

不要信任浏览器提供的Filename:某些浏览器会发送其他人只发送文件名的完整路径。因此,您可以使用以下代码上传图片/文件

        //-----

        String path = Server.MapPath("~/content/public");
        if (Request.Files != null && Request.Files.Count > 0)
        {
            String fileExtension = System.IO.Path.GetExtension(Request.Files[0].FileName).ToLower();
            List<string> allowedExtensions = new List<string>(){".gif", ".png", ".jpeg", ".jpg" };

          if (allowedExtensions.Contains(fileExtension))
            {
                string fileName = Guid.NewGuid().ToString();
                Request.Files[0].SaveAs(path + fileName);
                product.ProductImg = fileName ;
            }
        }
       ///------

要显示此图像,请使用以下简单的img标记

  @{string imageUrl=Url.Content("~/content/public/"+Model.ProductImg); }
  <img src="@imageUrl" alt=""/>

这可以为您提供指导...或者您需要删除/\,如下所示

   string fileName = Guid.NewGuid().ToString();

    fileName +="_"+Request.Files[0].FileName.Split(new char[]{'/','\'}).ToList().LastOrDefault();