Hi SUJAYS,
Using the following two articles i have created the example.
Retrieve and display Word Files from database in browser in ASP.Net
Retrieve and display PDF Files from database in browser in ASP.Net
HTML
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="Upload" />
<hr />
<asp:GridView ID="gvFiles" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Name" HeaderText="File Name" />
<asp:TemplateField ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<a class="view" href="javascript:;" rel='<%# Eval("Id") %>'>View Word</a>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<hr />
<div id="word-container" style="display: none;"></div>
<div id="pdf_container" style="display: none;"></div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://unpkg.com/jszip/dist/jszip.min.js"></script>
<script type="text/javascript" src="Scripts/docx-preview.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.6.347/pdf.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.6.347/pdf_viewer.min.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(function () {
$("[id*=gvFiles] .view").click(function () {
var fileId = $(this).attr("rel");
$.ajax({
type: "POST",
url: "Default.aspx/GetFile",
data: "{fileId: " + fileId + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
$('#word-container').hide();
$('#pdf_container').hide();
if (r.d.ContentType == "application/pdf") {
LoadPdfFromBlob(r.d.Data);
} else {
$('#word-container').show();
PreviewDoc(r);
}
},
error: function (r) {
alert(response.responseText);
}
});
});
});
function PreviewDoc(r) {
//Convert BLOB to File object.
var doc = new File([new Uint8Array(r.d.Data)], r.d.ContentType);
//If Document not NULL, render it.
if (doc != null) {
//Set the Document options.
var docxOptions = Object.assign(docx.defaultOptions, {
useMathMLPolyfill: true
});
//Reference the Container DIV.
var container = document.querySelector("#word-container");
//Render the Word Document.
docx.renderAsync(doc, container, null, docxOptions);
}
};
var pdfjsLib = window['pdfjs-dist/build/pdf'];
pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.6.347/pdf.worker.min.js';
var pdfDoc = null;
var scale = 1; //Set Scale for zooming PDF.
var resolution = 1; //Set Resolution to Adjust PDF clarity.
function LoadPdfFromBlob(blob) {
//Read PDF from BLOB.
pdfjsLib.getDocument({ data: blob }).promise.then(function (pdfDoc_) {
pdfDoc = pdfDoc_;
//Reference the Container DIV.
var pdf_container = document.getElementById("pdf_container");
pdf_container.innerHTML = "";
pdf_container.style.display = "block";
//Loop and render all pages.
for (var i = 1; i <= pdfDoc.numPages; i++) {
//RenderPage(pdf_container, i);
pdfDoc.getPage(i).then(function (page) {
//Create Canvas element and append to the Container DIV.
var canvas = document.createElement('canvas');
canvas.id = 'pdf-' + i;
ctx = canvas.getContext('2d');
pdf_container.appendChild(canvas);
//Create and add empty DIV to add SPACE between pages.
var spacer = document.createElement("div");
spacer.style.height = "20px";
pdf_container.appendChild(spacer);
//Set the Canvas dimensions using ViewPort and Scale.
var viewport = page.getViewport({ scale: scale });
canvas.height = resolution * viewport.height;
canvas.width = resolution * viewport.width;
//Render the PDF page.
var renderContext = {
canvasContext: ctx,
viewport: viewport,
transform: [resolution, 0, 0, resolution, 0, 0]
};
page.render(renderContext);
});
}
});
};
</script>
Namespaces
C#
using System.IO;
using System.Configuration;
using System.Data.SqlClient;
using System.Web.Services;
VB.Net
Imports System.IO
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Web.Services
Code
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
}
}
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT Id, Name FROM tblFiles";
cmd.Connection = con;
con.Open();
gvFiles.DataSource = cmd.ExecuteReader();
gvFiles.DataBind();
con.Close();
}
}
}
protected void Upload(object sender, EventArgs e)
{
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
string contentType = FileUpload1.PostedFile.ContentType;
using (Stream fs = FileUpload1.PostedFile.InputStream)
{
using (BinaryReader br = new BinaryReader(fs))
{
byte[] bytes = br.ReadBytes((Int32)fs.Length);
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string query = "INSERT INTO tblFiles VALUES (@Name, @ContentType, @Data)";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("@Name", filename);
cmd.Parameters.AddWithValue("@ContentType", contentType);
cmd.Parameters.AddWithValue("@Data", bytes);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
Response.Redirect(Request.Url.AbsoluteUri);
}
[WebMethod]
public static object GetFile(int fileId)
{
byte[] bytes;
string fileName, contentType;
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT Name, Data, ContentType FROM tblFiles WHERE Id = @Id";
cmd.Parameters.AddWithValue("@Id", fileId);
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
sdr.Read();
bytes = (byte[])sdr["Data"];
contentType = sdr["ContentType"].ToString();
fileName = sdr["Name"].ToString();
}
con.Close();
}
}
return new { FileName = fileName, ContentType = contentType, Data = bytes };
}
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
BindGrid()
End If
End Sub
Private Sub BindGrid()
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand()
cmd.CommandText = "SELECT Id, Name FROM tblFiles"
cmd.Connection = con
con.Open()
gvFiles.DataSource = cmd.ExecuteReader()
gvFiles.DataBind()
con.Close()
End Using
End Using
End Sub
Protected Sub Upload(sender As Object, e As EventArgs)
Dim filename As String = Path.GetFileName(FileUpload1.PostedFile.FileName)
Dim contentType As String = FileUpload1.PostedFile.ContentType
Using fs As Stream = FileUpload1.PostedFile.InputStream
Using br As New BinaryReader(fs)
Dim bytes As Byte() = br.ReadBytes(CType(fs.Length, Long))
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr)
Dim query As String = "INSERT INTO tblFiles VALUES (@Name, @ContentType, @Data)"
Using cmd As New SqlCommand(query)
cmd.Connection = con
cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = filename
cmd.Parameters.Add("@ContentType", SqlDbType.VarChar).Value = contentType
cmd.Parameters.Add("@Data", SqlDbType.Binary).Value = bytes
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
End Using
End Using
Response.Redirect(Request.Url.AbsoluteUri)
End Sub
<WebMethod>
Public Shared Function GetFile(ByVal fileId As Integer) As Object
Dim bytes As Byte()
Dim fileName As String, contentType As String
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand()
cmd.CommandText = "SELECT Name, Data, ContentType FROM tblFiles WHERE Id = @Id"
cmd.Parameters.AddWithValue("@Id", fileId)
cmd.Connection = con
con.Open()
Using sdr As SqlDataReader = cmd.ExecuteReader()
sdr.Read()
bytes = DirectCast(sdr("Data"), Byte())
contentType = sdr("ContentType").ToString()
fileName = sdr("Name").ToString()
End Using
con.Close()
End Using
End Using
Return New With {.FileName = fileName, .ContentType = contentType, .Data = bytes}
End Function