我正在尝试使用asp.net mvc 5
中的实体框架将图片保存在文件夹中并将路径存储在数据库中。我做到了,但我有一些问题。
DB中的图像路径保存如下:
C:UsersShimaDocumentsVisual Studio 2013ProjectsNP1NP1ImagesSubGoods2.jpg
如何将其更改为:~/Images/SubGoods/2.jpg
??
我想把图像名称改为primary key id
,我用了pic =Convert.ToString( subgood.SubGoodID);
,但它保存了Zero:
C:UsersShimaDocumentsVisual Studio 2013ProjectsNP1NP1ImagesSubGoods
它总是保存0
。我知道这是因为那一行的主键还没有生成。我的代码primary Key id
是在哪里生成的?
public ActionResult AddSubGood(SubGood subgood, HttpPostedFileBase UploadImage)
{
var MainGoodId = subgood.FKMainGoodID;
SubGoodRepositories blSubGood = new SubGoodRepositories();
string path="";
if (UploadImage != null)
{
string pic = System.IO.Path.GetFileName(UploadImage.FileName);
pic =Convert.ToString( subgood.SubGoodID);
path = System.IO.Path.Combine(
Server.MapPath("~/Images/SubGoods"), pic);
}
if (ModelState.IsValid)
{
subgood.FKMainGoodID = MainGoodId;
UploadImage.SaveAs(path);
subgood.SubGoodImage = path;
if (blSubGood.Add(subgood))
{
return JavaScript("alert('saved');");
}
else
{
return JavaScript("alert('didn't saved');");
}
}
else
{
return JavaScript("alert('error');");
}
}
您应该只保存文件名:
var fileName = Path.GetFileName(UploadImage.FileName);
然后,当你想为用户获取文件时,你可以简单地用特定的路径寻址文件名:
<img src="~/Content/Uploaded/@item.fileName" .../>
您也可以使用Guid
:生成随机文件名
var rondom = Guid.NewGuid() + fileName;
Server.MapPath将返回您的虚拟路径(您不需要),您可以创建另一个变量并像这样连接:
string DbPath = "~/Images/SubGoods/"; // better to store in web.config file
DbPath = DbPath + ""//here you can query in table and find the last inserted primary key and increment it with '1'