In this article, we see how read and write images to the database.
Let us start off by first creating a sample table in database. Run the following
script in oracle database.
Code: Database Table Script:
CREATE TABLE DOC_MAS (
DOC_ID NUMBER(10,0),
DOC_NAME VARCHAR2(200),
DOC_DATA BLOB
);
Code:frmUploadViewFile.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="frmUploadViewFile.aspx.cs"
Inherits="LearnAsp.Net.ControlDemo.ViewFile.frmUploadViewFile" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Validator Demo</title>
<style>
html
{
background-color: #35e0d8;
}
.column
{
float: left;
width: 300px;
margin-left: 10px;
background-color: white;
border: solid 1px black;
padding: 10px;
border-radius: 25px;
}
.column2
{
float: left;
width: 40%;
margin-left: 10px;
background-color: white;
border: solid 1px black;
padding: 10px;
border-radius: 25px;
}
fieldset
{
background-color: #e0b00040;
border: solid 2px #d81a72;
border-radius: 20px;
color: Black;
}
</style>
<style type="text/css">
.Popup
{
display: inline-block;
background-color: #F0F3F4;
border: 2px solid #094791; /*box-shadow: 8px 8px 5px #888888;*/
-moz-box-shadow: 3px 3px 4px #444;
-webkit-box-shadow: 3px 3px 4px #444;
box-shadow: 3px 3px 4px #444;
-ms-filter: "progid:DXImageTransform.Microsoft.Shadow(Strength=4, Direction=135, Color='#444444')";
filter: progid:DXImageTransform.Microsoft.Shadow(Strength=4, Direction=135, Color='#444444');
}
.FixedHeader
{
position: absolute;
font-weight: bold;
}
.form-control2, .single-line
{
background-color: #FFFFFF !important;
background-image: none !important;
border: 1px solid #CECFCF !important;
border-radius: 1px !important;
color: inherit !important;
display: block;
padding: 2px 3px !important;
transition: border-color 0.15s ease-in-out 0s, box-shadow 0.15s ease-in-out 0s !important;
width: 100% !important;
font-size: 13px !important;
}
</style>
<script>
function closeMsgPopupnew1() {
$find("mpeMsg2").hide();
debugger;
return false;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="id" runat="server">
</asp:ScriptManager>
<!-- ------------------------------------------------ -->
<cc1:ModalPopupExtender ID="popMsg1" runat="server" BehaviorID="mpeMsg2" TargetControlID="hdnPop6"
PopupControlID="pnlMessage2" CancelControlID="imgClose3">
</cc1:ModalPopupExtender>
<asp:HiddenField ID="hdnPop6" runat="server" />
<asp:Panel ID="pnlMessage2" runat="server" CssClass="Popup" Style="width: 460px;
height: 400px; display: none;">
<%-- display: none; --%>
<asp:Image ID="imgClose3" ToolTip="Close" runat="server" Style="z-index: -1; float: right;
visibility: visible; margin-top: -15px; margin-right: -15px;" onclick="closeMsgPopupNew1();"
ImageUrl="../../Image/closebtn.png" />
<center>
<br />
<div>
<asp:UpdatePanel ID="UpdatePanel3" runat="server" UpdateMode="conditional">
<ContentTemplate>
<table width="90%">
<tr>
<td align="center">
<asp:Image ID="imgDoc" Style="max-height: 380px; max-width: 400px; height: auto;
width: auto;" runat="server" />
<embed id="pdfDoc" runat="server" width="400" height="380" />
<%--src="@Url.Content(path)"--%>
<br />
<br />
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</center>
</asp:Panel>
<!-- ------------------------------------------------ -->
<div class="column">
<fieldset>
<legend>Save Document In Database</legend>
<asp:Label ID="lblName" Width="100" AssociatedControlID="fuDocUpload" runat="server">
Browser Document:</asp:Label><asp:FileUpload ID="fuDocUpload" runat="server" ValidationGroup="Upload" />
<br />
<br />
<asp:Button runat="server" ID="btnUpload" Text="UpLoad Document" ValidationGroup="Upload" CssClass="form-control2"
OnClick="btnUpload_Click" />
</fieldset>
</div>
<br />
<br >
<div style="clear: both;"></div>
<div ><h3> Uploaded Document List </h3>
<asp:GridView ID="grdDoc" runat="server" AlternatingRowStyle-CssClass="GrdAltRow" BackColor="#e6e1e1" PageSize="#ff3a3a"
Width="300px" AutoGenerateColumns="false" OnRowCommand="grdDoc_RowCommand" AutoGenerateSelectButton="true">
<Columns>
<asp:BoundField HeaderText="Doc ID" DataField="doc_id" />
<asp:BoundField HeaderText="Documet Name" DataField="doc_name" />
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
Code: frmUploadViewFile.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OracleClient;
using System.IO;
using System.Configuration;
using System.Data;
using System.Runtime.InteropServices;
using LearnAspClassLib.Method;
namespace LearnAsp.Net.ControlDemo.ViewFile
{
public static class FileType
{
public static int MimeSampleSize = 256;
public static string DefaultMimeType = "application/octet-stream";
[DllImport(@"urlmon.dll", CharSet = CharSet.Auto)]
private extern static uint FindMimeFromData(
uint pBC,
[MarshalAs(UnmanagedType.LPStr)] string pwzUrl,
[MarshalAs(UnmanagedType.LPArray)] byte[] pBuffer,
uint cbSize,
[MarshalAs(UnmanagedType.LPStr)] string pwzMimeProposed,
uint dwMimeFlags,
out uint ppwzMimeOut,
uint dwReserverd
);
public static string GetMimeFromBytes(byte[] data)
{
try
{
uint mimeType;
FindMimeFromData(0, null, data, (uint)MimeSampleSize, null, 0, out mimeType, 0);
var mimePointer = new IntPtr(mimeType);
var mime = Marshal.PtrToStringUni(mimePointer);
Marshal.FreeCoTaskMem(mimePointer);
return mime ?? DefaultMimeType;
}
catch
{
return DefaultMimeType;
}
}
}
public partial class frmUploadViewFile : System.Web.UI.Page
{
#region "MessageAlert" Show Alert Popup Message
public void MessageAlert(String Msg, String WinLoc)
{
String str = "";
str = "alert('|| " + Msg + " ||');";
if (WinLoc != "")
str += "window.location = '" + WinLoc + "';";
ScriptManager.RegisterStartupScript(this, typeof(Page), UniqueID, str, true);
return;
}
#endregion
//--------------------------------------------------------------------------------------------------
protected void btnUpload_Click(object sender, EventArgs e)
{
try
{
String strFileName, strFileExtension, strQuery;
OracleConnection objConn;
OracleCommand objCmd;
if (fuDocUpload.PostedFile.ContentLength > 0)
{
// Get the File name and Extension
strFileName = Path.GetFileName(fuDocUpload.PostedFile.FileName);
strFileExtension = Path.GetExtension(fuDocUpload.PostedFile.FileName);
//
// Extract the content of the Document into a Byte array
int intlength = fuDocUpload.PostedFile.ContentLength;
Byte[] byteData = new Byte[intlength];
fuDocUpload.PostedFile.InputStream.Read(byteData, 0, intlength);
//
// Save the file to the DB
string strConn = ConfigurationManager.ConnectionStrings["LearnAsp"].ToString();
objConn = new OracleConnection(strConn);
//
strQuery = "INSERT INTO doc_mas(doc_id,doc_name,doc_data) VALUES (seq_docid.nextval,";
strQuery += "'" + strFileName + "', ";
strQuery += " :DocData)";
//
OracleParameter blobParameter = new OracleParameter();
blobParameter.ParameterName = "DocData";
blobParameter.OracleType = OracleType.Blob;
blobParameter.Direction = ParameterDirection.Input;
blobParameter.Value = byteData;
objCmd = new OracleCommand(strQuery, objConn);
objCmd.Parameters.Add(blobParameter);
//
objConn.Open();
objCmd.ExecuteNonQuery();
objConn.Close();
//lblMsg.Text = "Document Uploaded Succesfully";
MessageAlert("Document Uploaded Succesfully", "");
fill_grid();
}
else
MessageAlert("Plz Select the document...", "");
}
catch (Exception ex)
{
//lblMsg.Text = " Error uploading Document: " + ex.Message.ToString();
MessageAlert(" Error uploading Document: " + ex.Message.ToString(), "");
}
}
protected void grdDoc_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.ToString().ToUpper() == "SELECT")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow selectedRow = grdDoc.Rows[index];
String SelDocId = selectedRow.Cells[1].Text;
ViewDoc(SelDocId);
}
}
protected void Page_Load(object sender, EventArgs e)
{
fill_grid();
}
public void fill_grid()
{
try
{
String Query = "select * from doc_mas ";
DataTable TblPrabhagSummary = (DataTable)MainClass.QueryExcute(Query);
if (TblPrabhagSummary.Rows.Count > 0)
{
grdDoc.DataSource = TblPrabhagSummary;
grdDoc.DataBind();
}
else
{
grdDoc.DataSource = null;
grdDoc.DataBind();
MessageAlert(" || Record Not Found || ", "");
return;
}
}
catch (Exception ex)
{
MessageAlert(ex.ToString(), "");
}
}
public void ViewDoc(String DocID)
{
String strFileName, strFileExtension;
OracleConnection objConn;
OracleCommand objCmd;
// Retrieve Details from the DB
string strConn = ConfigurationManager.ConnectionStrings["LearnAsp"].ToString();
objConn = new OracleConnection(strConn);
objCmd = new OracleCommand("SELECT doc_name, doc_data From doc_mas Where doc_id = " + DocID, objConn);
objConn.Open();
OracleDataReader dr = objCmd.ExecuteReader();
dr.Read();
strFileName = dr.GetString(0);
strFileExtension = "";
Byte[] byteDoc = new Byte[(dr.GetBytes(1, 0, null, 0, int.MaxValue))];
dr.GetBytes(1, 0, byteDoc, 0, byteDoc.Length);
dr.Close();
objConn.Close();
//
String fileEx = FileType.GetMimeFromBytes(byteDoc);
strFileExtension = fileEx;
Response.Clear();
Response.Buffer = true;
if (strFileExtension.ToUpper() == ".DOC" || strFileExtension.ToUpper() == ".DOCX")
{
Response.ContentType = "application/vnd.ms-word";
Response.AddHeader("content-disposition", "attachment;filename=" + strFileName + "." + strFileExtension);
}
else if (strFileExtension.ToUpper() == ".XLS" || strFileExtension.ToUpper() == ".XLSX")
{
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("content-disposition", "attachment;filename=" + strFileName + "." + strFileExtension);
}
else if (strFileExtension.ToLower().Contains("image"))
{
popMsg1.Show();
imgDoc.ImageUrl = "data:image;base64," + Convert.ToBase64String(byteDoc);
popMsg1.Y = 150;
}
else if (strFileExtension.ToLower().Contains("pdf"))
{
popMsg1.Show();
string base64String = Convert.ToBase64String(byteDoc);
var pdfUrl = "data:application/pdf;base64," + base64String;
pdfDoc.Attributes.Add("src", pdfUrl);
popMsg1.Y = 150;
}
}
}
}
Output:
No comments:
Post a Comment
Please do not enter any spam link in the comment box.