问题描述:

Here is my code that uploads a file with the path in a folder named Books , i want only the path to be stored in the database, and then fetch the files from the Books folder based on the path. Can someone guide me on how to go about.. below is my code and i am using asp.net mvc 4 and entity framework.

 [HttpPost]

public ActionResult upload(HttpPostedFileBase file)

{

//verify that the file is selected and not empty

if (file != null && file.ContentLength > 0)

{

//getting the name of the file

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

//store file in the Books folder

var path = Path.Combine(Server.MapPath("~/BOOKS"), fileName);

file.SaveAs(path);

}

return View();

}

网友答案:

If I am understanding you correctly, you want to store a string for the book path in the database and the book file under ~/Books?

  • You've already gotten the saving to "~/Books" part down
  • Create a database table with a few fields in it (ID, BookTitle, BookPath), get your model into the application (whatever method you chose; entity framework, etc), then code the logic:
    [HttpPost]
    public ActionResult upload(HttpPostedFileBase file)
    {
        //verify that the file is selected and not empty
        if (file != null && file.ContentLength > 0)
        {
            //getting the name of the file
            var fileName = Path.GetFileName(file.FileName);

            //store file in the Books folder
            var path = Path.Combine(Server.MapPath("~/BOOKS"), fileName);
            try{
                file.SaveAs(path);
                db.Table.Add(new Book{BookTitle: "Whatever", BookPath: path});
                db.SaveChanges();
            }catch(Exception ex){

            }
        }
        return View();
    }
相关阅读:
Top