Sunday, February 2, 2014

File Upload and save path to Database in asp.net MVC code first

Introduction: In this article today I am going to explain how we can File Upload and save path to Database in asp.net MVC code first

Description:

To upload image and save image path to database follow the below given steps:

Step 1:
 I have added Class to Model and name it FileUpload.cs:

using System.ComponentModel.DataAnnotations;

public class FileUpload
    {
        [Key]
        public int ID { get; set; }
        public string length { get; set; }

    }
After that add the Class to ProjectContext.cs.

public DbSet<FileUpload> FileUploads { get; set; }

How to add the class sees this article Create, Read, Update and Delete in Asp.net with MVC 4 Razor view Engine using Entity framework with Code first approach.


Step 2:
Add a controller to project.  In this example I named it FileUploadController.cs and write the code:

using MVCAPPLICATION.Models;
using System.IO;

private ProjectContext db = new ProjectContext();
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Index(FileUpload upload, HttpPostedFileBase file)
        {
            if (file.ContentLength > 0)
            {              
                var fileName = Path.GetFileName(file.FileName);
                var guid = Guid.NewGuid().ToString();
                var path = Path.Combine(Server.MapPath("~/uploads"), guid + fileName);
                file.SaveAs(path);
                string fl = path.Substring(path.LastIndexOf("\\"));
                string[] split = fl.Split('\\');
                string newpath = split[1];
                string imagepath = "~/uploads/" + newpath;
                upload.length = imagepath;
                db.FileUploads.Add(upload);
                db.SaveChanges();
            }
            TempData["Success"] = "Upload successful";
            return RedirectToAction("Index");
        }

Step 3:
Add a View for Index and design as shown below:

<form action="" method="post" enctype="multipart/form-data">
<label for="file">Upload File:</label><input type="file" name="file" id="file" />
  <input type="submit" />
    @if (TempData["Success"] != null)
{
    <div class="success">
        <p>@TempData["Success"].ToString()</p>
    </div>
}
</form>


Build and run the project.

Is this article helpful for you?

If yes post your comment to appreciate my work and fell free to contact me. You can like me on Facebook, Google+, Linkedin and Twitter via hit on Follow us Button and also can get update follow by Email.

17 comments:

  1. Replies
    1. which is not understandable........ where are you getting problem.....please tell me i will help you....

      Delete
  2. how to add below class
    {{{{{{{
    After that add the Class to ProjectContext.cs.

    public DbSet FileUploads { get; set; }
    }}}}}
    plz upload video if u have...

    ReplyDelete
  3. What is db?Why u have used this?
    db.FileUploads.Add(upload);
    db.SaveChanges();

    its giving me error

    ReplyDelete
    Replies
    1. Db is the object of Database Entities. it represents the database model.. Hope it makes sense...if u getting any problem plz let me know

      Delete
  4. i'm having a problem with the path, it says cant find part of the path

    ReplyDelete
    Replies
    1. you are not providing the accurate path. Provide the accurate path of folder.

      Delete
  5. i have problem with to be save in db in path

    ReplyDelete
    Replies
    1. Code is tested and working fine. Can you tell me what error you are getting?

      Delete
  6. Nice Work and also thanks for short and understandable code .Butt i have to need the code of how this image will show on index .Do you have ?if do then send me agin thanks in advance

    ReplyDelete
  7. Nice Work and also thanks for short and understandable code .Butt i have to need the code of how this image will show on index .Do you have ?if do then send me agin thanks in advance

    ReplyDelete
  8. try something like 'db.Entry(team).State = EntityState.Added;' where team is the variable of type model FileUpload instead of db.SaveChanges.

    ReplyDelete
  9. Much understandable code..after importing
    using System.IO;
    using System.Web.UI.WebControls; still showing error on following code
    upload.length = imagepath;
    db.FileUploads.Add(upload);

    ReplyDelete
  10. while editing the record if we are changing only name of the record and giving same file path its showing null pointer exception at
    public ActionResult Index(FileUpload upload, HttpPostedFileBase *file*)
    **********nullpointer exception**********

    ReplyDelete