简体   繁体   中英

WebImage helper not creating correct path to image?

My problem is with the following piece of code. I have built WebPages app where this chunk of code works perfectly, however, in my MVC5 app it copies only the local path from my PC to MSSQL database, without a GUID even. The piece of code is:

CONTROLLER:

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

Also how do I prevent this code from writing NULL to database in case that the user doesn't want to change the image?

Don't trust Filename provided by browser: some browsers send the full path others send only the file name. So you'd vetter use the following code to upload your picture/file

        //-----

        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 ;
            }
        }
       ///------

and to display this image, use a simple img tag as follows

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

This can provide you with a guid...or you'll need to remove / or \\ as follows

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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