ASP.NET MVC 3: Save .pdf file to database and download pdf file from databse.

The article previous I was introduce about Using Microsoft Report Viewer in ASP.NET MVC3. In this article I will introduce about how to save .pdf file to database in ASP.NET MVC 3.

1. Create a new database to store pdf file and set named Database.mdf.

2. Create a new table and set named DataFiles

image

3. Create a new DataFileModel.edmx under Models folder.

image

4.Add two buttons Save and Download in Index.aspx file

</pre>
<div style="float: left; width: 100%;"><% using(Html.BeginForm("SaveFile","Home")) { %>
 <input style="float: left;" type="submit" value="Save file" />
 <%} %>

 <% using(Html.BeginForm("Download","Home")) { %>
 <input style="float: left;" type="submit" value="Download" />
 <%} %></div>
<pre>

5. Create method SaveFile in HomeController.

public ActionResult SaveFile()
        {
            LocalReport localReport = new LocalReport();
            localReport.ReportPath = Server.MapPath("~/Reports/rptCustomer.rdlc");
            ReportDataSource reportDataSource = new ReportDataSource("Customer",
                new CustomerModel().GetAllCustomer());
            localReport.DataSources.Add(reportDataSource);

            string reportType = "pdf";
            string mimeType;
            string encoding;
            string fileNameExtension;
            //The DeviceInfo settings should be changed based on the reportType
            //http://msdn2.microsoft.com/en-us/library/ms155397.aspx
            string deviceInfo =
                "" +
                "  PDF" +
                "  8.5in" +
                "  11in" +
                "  0.5in" +
                "  1in" +
                "  1in" +
                "  0.5in" +
                "";
            Warning[] warnings;
            string[] streams;
            byte[] renderedBytes;
            //Render the report
            renderedBytes = localReport.Render(
                reportType,
                deviceInfo,
                out mimeType,
                out encoding,
                out fileNameExtension,
                out streams,
                out warnings);

            // Save to Database
            DataFile dataFile = new DataFile {
                FileName = "Customer",
                FileData = renderedBytes,
                FileExtension = ".pdf"
            };

            bool Status;
            try
            {
                context.DataFiles.AddObject(dataFile);
                context.SaveChanges();
                ViewBag.Status = true;
                return View();
            }
            catch {
                ViewBag.Status = false;
                return View();
            }
        }

6. Create SaveFile.aspx to display message after save file

</pre>
<h2></h2>
<pre>
 <% if (ViewBag.Status == true)      { %></pre>
<div>Save file to Database is successful!</div>
<pre>
     <%         }      else      {       %></pre>
<div>Save file to Database is fail!</div>
<pre>
     <%       } %>

7. Build and run website so click Save button to save file to database.

image

8. Open database to check data.

image

9. The next we will implement action download pdf file from database.

Create a new method Download in HomeController.

public ActionResult Download()
        {
            DataFile dataFile = context.DataFiles.SingleOrDefault(p => p.Id == 1);
            byte[] fileData = dataFile.FileData;

            // Generate PDF file
            Warning[] warnings = null;
            String[] streamids = null;
            String mimeType = null;
            String encoding = null;
            String extension = null;

            Response.Clear();
            Response.ClearHeaders();
            Response.ClearContent();
            Response.ContentType = mimeType;
            Response.AddHeader("Content-Disposition", string.Format("attachment; filename=Customer.pdf"));
            Response.BinaryWrite(fileData);
            Response.End();

            return RedirectToAction("Index");
        }

10. Build and run website, so click Download button to download pdf file.

image

View pdf file after download.

image

Happy coding!

Advertisements
This entry was posted in ASP.NET MVC. Bookmark the permalink.

3 Responses to ASP.NET MVC 3: Save .pdf file to database and download pdf file from databse.

  1. karthik says:

    how should i do it using ado.net

  2. Pingback: Medicare Card » aspx Search Database

  3. Pingback: Medicare Code PDF » aspx Search Database

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s