Saturday 29 September 2018

Display uploaded file content from Database in MVC


In this article I would like to know you about display file content from  Database to the  in iframe. To create the database I used Code First approach using Entityframework in MVC application.
For that, Take an empty MVC application and add a class named Database and implement the interface DbContext as below :

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace MVC_DisplayFileInIFrame_Jquery.Models
{
    public class FileUploadDb : DbContext
    {
        public FileUploadDb() : base("DefaultConnection") // DefaultConnection is the name of the connectionString in web.config file
        { }

        public DbSet FileUploads { get; set; }
       

    }

    public class FileUpload
    {
        [Key]
        public int Id { get; set; }
        [Timestamp]
        public byte[] RowVersion { get; set; }
        public string FileName { get; set; }
        public double FileContentLength { get; set; }
        public string FileContentType { get; set; }
        public string FileDescription { get; set; }
        public byte[] UploadedFile { get; set; }

    }
}

The connectionString in the web.config is as follows :

        
 

Now open the Nuget Package Manger Console and Enable Migrations and Add Migration with name to identify the migration, and update database, now DB will be created in the SqlServer management studio, The below will show the commands performed for Database creation :
PM> Enable-Migrations -contexttypename FileUploadDb
Checking if the context targets an existing database...
Code First Migrations enabled for project MVC-DisplayFileInIFrame-Jquery.
PM> add-migration 'Create FileUploadDb database'
Scaffolding migration 'Create FileUploadDb database'.
The Designer Code for this migration file includes a snapshot of your current Code First model. This snapshot is used to calculate the changes to your model when you scaffold the next migration. If you make additional changes to your model that you want to include in this migration, then you can re-scaffold it by running 'Add-Migration Create FileUploadDb database' again.
PM> update-database
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Applying explicit migrations: [201809300114045_Create FileUploadDb database].
Applying explicit migration: 201809300114045_Create FileUploadDb database.
Running Seed method.
PM>



Now After running this commands, a Migrations folder is created with two .cs file, one is a class name with what we have added at the add-migration name will be created with Up() and Down() methods which are auto generated to create and drop the database and another one is a sealed Configuration class that inherits DBMigrationsConfiguration

The auto generated files codes as follows :

201809300114045_Create FileUploadDb database.cs



namespace MVC_DisplayFileInIFrame_Jquery.Migrations
{
    using System;
    using System.Data.Entity.Migrations;
    
    public partial class CreateFileUploadDbdatabase : DbMigration
    {
        public override void Up()
        {
            CreateTable(
                "dbo.FileUploads",
                c => new
                    {
                        Id = c.Int(nullable: false, identity: true),
                        RowVersion = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion"),
                        FileName = c.String(),
                        FileContentLength = c.Double(nullable: false),
                        FileContentType = c.String(),
                        FileDescription = c.String(),
                        UploadedFile = c.Binary(),
                    })
                .PrimaryKey(t => t.Id);
            
        }
        
        public override void Down()
        {
            DropTable("dbo.FileUploads");
        }
    }
}

Configuration.cs
namespace MVC_DisplayFileInIFrame_Jquery.Migrations
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;

    internal sealed class Configuration : DbMigrationsConfiguration
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
        }

        protected override void Seed(MVC_DisplayFileInIFrame_Jquery.Models.FileUploadDb context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet.AddOrUpdate() helper extension method 
            //  to avoid creating duplicate seed data. E.g.
            //
            //    context.People.AddOrUpdate(
            //      p => p.FullName,
            //      new Person { FullName = "Andrew Peters" },
            //      new Person { FullName = "Brice Lambson" },
            //      new Person { FullName = "Rowan Miller" }
            //    );
            //
        }
    }
}


Now create a model name FileUploadModel as below :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MVC_DisplayFileInIFrame_Jquery.Models
{
    public class FileUploadModel
    {
        public string FileDescription { get; set; }
        public string UploadedFile { get; set; }
        public string FileBase64String { get; set; }
    }
}

And Now create a controller name FileUpload and write the below code :
using MVC_DisplayFileInIFrame_Jquery.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVC_DisplayFileInIFrame_Jquery.Controllers
{
    public class FileUploadController : Controller
    {
        // GET: FileUpload
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Index(FileUploadModel fu)
        {
            var file = Request.Files["UploadedFile"];
            var stream = new MemoryStream();
            file.InputStream.CopyTo(stream);
            using (var db = new FileUploadDb())
            {
                FileUpload fuModel = new FileUpload();
                fuModel.FileContentLength = file.ContentLength;
                fuModel.FileContentType = file.ContentType;
                fuModel.FileName = file.FileName;
                fuModel.FileDescription = fu.FileDescription;
                fuModel.UploadedFile = stream.ToArray();
                db.FileUploads.Add(fuModel);
                db.SaveChanges();
            }
            string fpBase64string = Convert.ToBase64String(stream.ToArray());
            // string mimeType = o.GetMimeType(fileExtension);
            fu.FileBase64String = String.Format("data:{0};base64,{1}", file.ContentType, fpBase64string);
            return View(fu);
           // return View();
        }
    }
}

And now create a view and write the below code as follows :
@model MVC_DisplayFileInIFrame_Jquery.Models.FileUploadModel

@{
    ViewBag.Title = "Index";
}
@* if form contains input type 'file' then enctype = "multipart/form-data" should add to the Html.BeginForm  *@
@using (Html.BeginForm("Index", "FileUpload", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    

iframe using JQuery

@**@ @if (Model != null) { if (Model.FileBase64String != null) {
} else { } } else { }
}
Now run the application
Output :
After run the application it displays as below :



When you upload a file, it takes the file and save it in database in byte format by converting and return the byte format to base64 and display in the IFrame of view, it shows as below :



No comments:

Post a Comment

Note: only a member of this blog may post a comment.