Search code examples
asp.netasp.net-mvcuploadasp.net-mvc-5server.mappath

How change server map path and file name when file uploaded in asp.net mvc?


I am trying to save picture in folder and store path in database using entity framework in asp.net mvc 5. I did it but I have some problems .

image path in DB saved like this :

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

How can I change it to: ~/Images/SubGoods/2.jpg ??

and I want to change image name to it's primary key id and I used pic =Convert.ToString( subgood.SubGoodID); to do it, but it saves Zero :

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

It saves always 0 .I know that's because Primary key in that line not generated yet . where of my codes primary Key id generated ?

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

    }

Solution

  • You should save only the file name:

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

    Then when you want to fetch the file for user you can simply address the file name with specific path:

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

    You can also generate a random file name using Guid:

    var rondom = Guid.NewGuid() + fileName;