Tuesday, 4 September 2012

How to upload Files in Mvc:

Hie.... today i gone throught this example here i done  storing files in both my disk as well in my database also....

In my view i'm rendering my form as folllows:

   <div class="divload">
     <input type="file" name="FileUpload1" id="FileUpload1" /><br />
     <input type="submit" name="Submit" id="Submit" value="Upload" />
    </div>

My page shows as follows
when using a fileupload now i'm checking whether the file selected or not by using the Fileupload.HasFile() Method as follows:


public static bool HasFile(this HttpPostedFileBase file)
{
  return (file != null && file.ContentLength > 0) ? true : false;
}


Here first i'm showing how to save the uploading file in disk that mean in our project solution nothing but in Disk  for that my controller will be as follows:

      public class HomeController : Controller
     {
  public ActionResult Index()
  {
    foreach (string upload in Request.Files)
    {
      if (!Request.Files[upload].HasFile()) continue;
      string path = AppDomain.CurrentDomain.BaseDirectory + "uploads/";
      string filename = Path.GetFileName(Request.Files[upload].FileName);
      Request.Files[upload].SaveAs(Path.Combine(path, filename));
    }
    return View();
  }
}
    here for this action the result will stores that uploading file to that "Uploads" folder in the project. and now next way of saving into Database here controller looks as follow :

And before that please create your DB table as bellow :
         
             CREATE TABLE [dbo].[FileStore](         
            [ID] [int] IDENTITY(1,1) NOT NULL,   
            [FileContent] [image] NOT NULL,   
            [MimeType] [nvarchar](50) NOT NULL,     
          [FileName] [nvarchar](50) NOT NULL        
         ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

result as that will creates your table with fields of ID, Filecontent as image, mimetype which shows you of which type it is, and Filename

Now my controller 'll be as follows :
foreach (string upload in Request.Files)
   {       if (!Request.Files[upload].HasFile()) continue;
string mimeType = Request.Files[upload].ContentType;  Stream fileStream = Request.Files[upload].InputStream; string fileName = Path.GetFileName(Request.Files[upload].FileName);
int fileLength = Request.Files[upload].ContentLength; byte[] fileData = new byte[fileLength];             fileStream.Read(fileData, 0, fileLength);
string connect = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
 using (var conn = new SqlConnection(connect))
   {
var qry = "INSERT INTO FileStore (FileContent, MimeType, FileName) VALUES (@FileContent, @MimeType, @FileName)";                var cmd = new SqlCommand(qry, conn);                cmd.Parameters.AddWithValue("@FileContent",fileData); cmd.Parameters.AddWithValue("@MimeType",mimeType);           cmd.Parameters.AddWithValue("@FileName",fileName);              conn.Open();       cmd.ExecuteNonQuery();               
}

No comments:

Post a Comment