0

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();
    }
2
  • 1
    What is the question/problem you have encountered? What exactly are you having difficulties with? Commented Nov 20, 2012 at 12:35
  • My question is that i want to upload books using a simple file upload tool in a folder i created named books. The file path has to be stored in the database and the book in the folder named books. Next, i want to fetch those books from the database based on the path. Commented Nov 20, 2012 at 17:41

1 Answer 1

2

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();
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.