File Upload and save path to Database in asp.net MVC code first - Free Asp.Net,MVC,AngularJs,Jquery,Javascript,Sql Server,WCF,Entity framework snippets and tutorial


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.

What do you think about this article?

If you found this article useful, please share and follow on Facebook, Twitter, Google Plus and other social media websites. To get free updates subscribe to newsletter. Please put your thoughts and feedback in comments section.

Share this

Share on FacebookTweet on TwitterPlus on Google+
loading...

17 comments

explain code

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

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

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

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

its giving me error

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

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

i have problem with to be save in db in path

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

you are not providing the accurate path. Provide the accurate path of folder.

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

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

This comment has been removed by the author.

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

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);

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**********


EmoticonEmoticon