我可以成功上传照片并将其插入数据库,但上传多张照片时遇到问题。这是我的产品型号:
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; }
这是我的控制者:
[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();
}
我想将照片的网址保存到coloumn imageUrl1,imageUrl2和imageUrl3。
答案 0 :(得分:1)
尝试这样的事情
[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();
}