在asp.net mvc上传文件时如何更改服务器映射路径和文件名?

时间:2016-01-05 06:25:53

标签: asp.net asp.net-mvc upload asp.net-mvc-5 server.mappath

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

数据库中的

图像路径保存如下:

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);来执行此操作,但它会保存为零:

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');");
        }

    }

2 个答案:

答案 0 :(得分: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'

答案 1 :(得分:1)

您应该只保存文件名:

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

然后,当您想要为用户获取文件时,您只需使用特定路径寻址文件名:

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

您还可以使用Guid生成随机文件名:

var rondom = Guid.NewGuid() + fileName;