Reputation: 25
I can successfully to upload and insert photos into a database, but I am having trouble when uploading multiple photos. This is my model class of product:
public int ID { get; set; }
public int ID_Category { get; set; }
public int ID_User { get; set; }
public string Name_Product { get; set; }
public Nullable<decimal> Price { get; set; }
public string Detail { get; set; }
public string Description { get; set; }
public Nullable<int> Reviews { get; set; }
public string imageUrl1 { get; set; }
public string imageUrl2 { get; set; }
public string imageUrl3 { get; set; }
public virtual Category Category { get; set; }
public virtual UserProfile UserProfile { get; set; }
And this is my controller:
[HttpPost]
public ActionResult AddProdct(Product DataProduct)
{
int UserId = WebSecurity.GetUserId(User.Identity.Name);
// var r = new List<Product>();
var Data = db.Product.Add(DataProduct);
Data.ID_User = UserId;
Data.ID_Category = DataProduct.ID_Category;
Data.Name_Product = DataProduct.Name_Product;
foreach(string file in Request.Files)
{
HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
if (hpf.ContentLength == 0)
continue;
string saveFileName = Path.GetFileName(hpf.FileName);
string location = Path.Combine(Server.MapPath("~/Images/Product"+ @"\" + saveFileName.Replace('+', '_')));
Request.Files[file].SaveAs(location);
Data.imageUrl1 = saveFileName;
}
db.SaveChanges();
}
I want to save my picture's URL to coloumn imageUrl1, imageUrl2 and imageUrl3.
Upvotes: 1
Views: 2987
Reputation: 3923
Try something like this
[HttpPost]
public ActionResult AddProdct(Product DataProduct)
{
int UserId = WebSecurity.GetUserId(User.Identity.Name);
// var r = new List<Product>();
var Data = db.Product.Add(DataProduct);
Data.ID_User = UserId;
Data.ID_Category = DataProduct.ID_Category;
Data.Name_Product = DataProduct.Name_Product;
// Count varible
int count = 0 ;
foreach(string file in Request.Files)
{
HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
if (hpf.ContentLength == 0)
continue;
string saveFileName = Path.GetFileName(hpf.FileName);
string location = Path.Combine(Server.MapPath("~/Images/Product"+ @"\" + saveFileName.Replace('+', '_')));
Request.Files[file].SaveAs(location);
// Data.imageUrl1 = saveFileName;
if ( i >= 3)
i = 0 ;
// Count + 1 each time
i++ ;
if (i == 1 )
{
Data.imageUrl1 = saveFileName ;
}
else if (i == 2)
{
Data.imageUrl2 = saveFileName ;
}
else if (i == 3 )
{
Data.imageUrl3 = saveFileName ;
}
}
db.SaveChanges();
}
Upvotes: 1