0

我正在尝试使用实体框架将图片保存在文件夹中并在数据库中存储路径asp.net mvc 5。我做到了,但我有一些问题。

DB中的图像路径保存如下:

C:\Users\Shima\Documents\Visual Studio 2013\Projects\NP1\NP1\Images\SubGoods\2.jpg

我怎样才能将其更改为: ~/Images/SubGoods/2.jpg??

我想将图像名称更改为它primary key id,我曾经pic =Convert.ToString( subgood.SubGoodID);这样做过,但它保存了 Zero :

C:\Users\Shima\Documents\Visual Studio 2013\Projects\NP1\NP1\Images\SubGoods\0

它总是保存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');");
        }

    }
4

2 回答 2

1

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'
于 2016-01-05T07:14:05.753 回答
1

您应该只保存文件名:

var fileName = Path.GetFileName(UploadImage.FileName);

然后,当您想为用户获取文件时,您可以简单地使用特定路径来处理文件名:

<img src="~/Content/Uploaded/@item.fileName" .../>

您还可以使用以下命令生成随机文件名Guid

var rondom = Guid.NewGuid() + fileName;
于 2016-01-05T07:18:29.887 回答