Translate

Wednesday, 30 January 2013

Uploading And Downloading Files/Images By Using Linq to sql in MVC3


Uploading the Images/Files And Downloaded the Uploaded Image/Files By Using Linq to sql

Create a Linq to Sql dbml file in model class and Build it...

Linq To Sql:

DBcontext.dbml  :

 FileDump

Set Pk(Id) and Set Auto increment

Id                int  
FileName     Varchar 
FileData       image

Controller Class:

Test.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVC3FileUploadDownloadLINQ.Models;

namespace MVC3FileUploadDownloadLINQ.Controllers
{
    public class TestController : Controller
    {
        //
        // GET: /Test/
       
        public ActionResult FileUpload(HttpPostedFileBase Files)
        {
            DBContextDataContext dataContext = new DBContextDataContext();
            foreach (string upload in Request.Files)
            {
                //create byte array of size equal to file input stream
                byte[] fileData = new byte[Request.Files[upload].InputStream.Length];
                //add file input stream into byte array
                Request.Files[upload].InputStream.Read(fileData, 0, Convert.ToInt32(Request.Files[upload].InputStream.Length));
                //create system.data.linq object using byte array
                System.Data.Linq.Binary binaryFile = new System.Data.Linq.Binary(fileData);
                //initialise object of FileDump LINQ to sql class passing values to be inserted
                FileDump record = new FileDump { FileData = binaryFile, FileName = System.IO.Path.GetFileName(Request.Files[upload].FileName) };
                //call InsertOnsubmit method to pass new object to entity
                dataContext.FileDumps.InsertOnSubmit(record);
                //call submitChanges method to execute implement changes into database
                dataContext.SubmitChanges();
            }
            var returnData = dataContext.FileDumps;
            ViewData.Model = returnData.ToList();
            return View();
        }

        public FileContentResult FileDownload(int id)
        {
            //declare byte array to get file content from database and string to store file name
            byte[] fileData;
            string fileName;
            //create object of LINQ to SQL class
            DBContextDataContext dataContext = new DBContextDataContext();
            //using LINQ expression to get record from database for given id value
            var record = from p in dataContext.FileDumps
                         where p.ID == id
                         select p;
            //only one record will be returned from database as expression uses condtion on primary field
            //so get first record from returned values and retrive file content (binary) and filename
            fileData = (byte[])record.First().FileData.ToArray();
            fileName = record.First().FileName;
            //return file and provide byte file content and file name
            return File(fileData, "text", fileName);
        }

    }
}



Views:

FileUpload.cshtml


@*@model MVC3FileUploadDownloadLINQ.Models.FileDump*@

@{
    ViewBag.Title = "FileUpload";
}

<h2>FileUpload</h2>
<div id="UploadSection">       
    @using (Html.BeginForm("FileUpload", "Test", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        <br />
        <p><input type="file" name="fileUpload1" /> </p>
        <p><input type="submit" value="Upload file" /></p>       
    } 
</div>


<div id="ShowList" title="File List">
        <table width="50%">
        <thead>
            <th>
                File ID
            </th>
            <th>
                File Name
            </th>
            <th>
                File Download
            </th>
        </thead>
        <tbody>
       
            @foreach(var rec in ViewData.Model)
            {
       
           <tr>
            <td>
                @rec.ID
            </td>
            <td>
                @rec.FileName
            </td>
            <td>
                @Html.ActionLink("Download", "Filedownload", new { id=rec.ID})        
            </td>
           </tr>
            }
        </tbody>
        </table>
    </div>




Thanks...

Happy Coding

Regards

Ur's Jagan

File Upload And Download By Using Linq to Sql in MVC3 Razor View(Jquery)


File Upload And Download By Using Linq

We start by creating a new ASP.NET MVC 3 web application and we add the file “jquery-filedrop.js” to the Scripts folder of the project. After this is done we modify the default layout “Views/Shared/_Layout.cshtml” to reference our newly added JavaScript library. In order to do is, add the following line to the head tag.

<script src="@Url.Content("~/Scripts/jquery.filedrop.js")" type="text/javascript"></script>


Controller Class::

Home.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;

namespace MVC3FileUploadDownloadLINQ.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
        private const string TempPath = @"D:\Temp";
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult UploadFiles(IEnumerable<HttpPostedFileBase> files)
        {
            foreach (HttpPostedFileBase file in files)
            {
                 string filePath = Path.Combine(TempPath, file.FileName);
            System.IO.File.WriteAllBytes(filePath, ReadData(file.InputStream));
            }
            return Json("All files have been successfully stored.");
        }
        private byte[] ReadData(Stream stream)
        {
            byte[] buffer = new byte[16 * 1024];
            using (MemoryStream ms = new MemoryStream())
            {
                int read;
                while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                return ms.ToArray();
            }
        }
    }
}

Views: File drag and drop in your jquery drop box and automatically it's dowload after droping your file...

Index.cshtml

@{

    ViewBag.Title = "Index";
}

 <style type="text/css">

    #dropZone {

        background: gray;

        border: black dashed 3px;

        width: 200px;

        padding: 50px;

        text-align: center;

        color: white;

    }

</style>

<script type="text/javascript">

    $(function () {

        $('#dropZone').filedrop({

            url: '@Url.Action("UploadFiles")',

            paramname: 'files',

            maxFiles: 5,

            dragOver: function () {

                $('#dropZone').css('background', 'blue');

            },

            dragLeave: function () {

                $('#dropZone').css('background', 'gray');

            },

            drop: function () {

                $('#dropZone').css('background', 'gray');

            },

            afterAll: function () {

                $('#dropZone').html('The file(s) have been uploaded successfully!');

            },

            uploadFinished: function (i, file, response, time) {

                $('#uploadResult').append('<li>' + file.name + '</li>');

            }
        });

    });

</script>



<h2>File Drag & Drop Upload Demo</h2>

<div id="dropZone">Drop your files here</div>

<br/>

Uploaded Files:

<ul id="uploadResult">
</ul>


Thanks
Happy Coding

Regards
Ur's Jagan

Image Upload and Download In MVC3


Image Upload and Download
 Table

dbo.FileStore

Id           int
FileContent  image
FileType     Varchar(50)
FileName     varchar(50) 


Controller:

HomeController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.Data.SqlClient;

namespace MVC3DispAndUpImage.Controllers
{
    public class HomeController : Controller
    {
       public bool HasFile(HttpPostedFileBase file)
        {
            return (file != null && file.ContentLength > 0) ? true : false;
        }

        //upload images in database one by one one if FileUpload contain file
        public ActionResult Index()
        {
            foreach (string upload in Request.Files)
            {
                if (!HasFile(Request.Files[upload])) continue;

                string fileType = 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);

                const string connect = @"Data Source=JAGAN-PC;Initial Catalog=MVC3;Integrated Security=True";
                using (var conn = new SqlConnection(connect))
                {
                    var qry = "INSERT INTO FileStore (FileContent, FileType, FileName)VALUES (@FileContent, @MimeType, @FileName)";
                    var cmd = new SqlCommand(qry, conn);
                    cmd.Parameters.AddWithValue("@FileContent", fileData);
                    cmd.Parameters.AddWithValue("@FileType", fileType);
                    cmd.Parameters.AddWithValue("@FileName", fileName);
                    conn.Open();
                    cmd.ExecuteNonQuery();
                }
            }
            return View();
        }
      
        //store file name in the list from the database
        //and store that list object in a ViewBag property
        public ActionResult Download()
        {
            const string connect = @"Data Source=JAGAN-PC;Initial Catalog=MVC3;Integrated Security=True";
            List<string> imgList = new List<string>();
            using (var conn = new SqlConnection(connect))
            {
                var qry = "SELECT FileContent, FileType, FileName FROM FileStore";
                var cmd = new SqlCommand(qry, conn);
                conn.Open();
                SqlDataReader rdr = cmd.ExecuteReader();
                while (rdr.Read())
                {
                    imgList.Add(rdr["FileName"].ToString());
                }
            }
            ViewBag.Images = imgList;
            return View();
        }

        //get the file id and return a file to the browser
        public FileContentResult GetFile(int id)
        {
            SqlDataReader rdr;
            byte[] fileContent = null;
            string mimeType = "";
            string fileName = "";
            const string connect = @"Data Source=JAGAN-PC;Initial Catalog=MVC3;Integrated Security=True";

            using (var conn = new SqlConnection(connect))
            {
                var qry = "SELECT FileContent, FileType, FileName FROM FileStore WHERE ID= @ID";
                var cmd = new SqlCommand(qry, conn);
                cmd.Parameters.AddWithValue("@ID", id);
                conn.Open();
                rdr = cmd.ExecuteReader();
                if (rdr.HasRows)
                {
                    rdr.Read();
                    fileContent = (byte[])rdr["FileContent"];
                    mimeType = rdr["FileType"].ToString();
                    fileName = rdr["FileName"].ToString();
                }
            }
            return File(fileContent, fileType, fileName);
        }

    }
}


Views:

Index.cshtml

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<html>
<head runat="server">
    <title>Index</title>
</head>
<body>
    <div>
        @{
            using (Html.BeginForm("", "home", FormMethod.Post, new { enctype ="multipart/form-data" }))
            {
        <input type="file" name="FileUpload1" /><br />
        <input type="file" name="FileUpload2" /><br />
       
        <input type="submit" name="Submit" id="Submit" value="Upload" /><br />
            }
        
        <h4>
            <a href="/Home/Download">Go for the Download</a></h4>
           
        }
    </div>
</body>
</html>

Download.cshtml

@{
    ViewBag.Title = "Download";
}

<h2>Download</h2>


<html>
<head runat="server">
    <title>Download</title>
</head>
<body>
    <div>
    <img src= "@Url.Content("~/Content/Images/CMGR.jpg")" alt="CMGR1.jpg" title="CMGR1.jpg" />
        @{
            int data = 1;

            foreach (string img in ViewBag.Images)
            {
               <h4> @Html.ActionLink(img, "GetFile/" + data++)</h4><br />
            <img src= "@Url.Content("img")" alt="ViewBag.Images" title="ViewBag.Images" />
          
            @*foreach(var item in Model)
            {
           
                @ if (ViewBag.Images != null)
                    {
                      <img src="@Url.Action("GetFile", "HomeController", new { id = item.Id })" alt="@item.FileContent" />
                       <img src="@Model.GetFile(item.Images)" alt="@item.FileContent"/>  
                    }
            }
            @Html.DisplayFor(img,"GetFile/",+data++)*@
          
                  if (data == 1)
                  {
                 <h2>No files are in the database!</h2>
               }
            }
       
        }
    </div>
</body>
</html>





Happy Coding

Regards
Ur's Jagan