Click here to Skip to main content
15,867,488 members
Articles / Web Development / ASP.NET
Article

Use Dynamsoft to Store and Retrieve Scanned Images from SQL Server in ASP.NET

11 Nov 2013CPOL3 min read 27.6K   447   5  
In this article, we will illustrate how to use document scan features in an ASP.NET web application to save scanned files as PDFs to an SQL Server database. We’ll also cover retrieval of image files and their display within your ASP.NET web page.

This article is in the Product Showcase section for our sponsors at CodeProject. These articles are intended to provide you with information on products and services that we consider useful and of value to developers.

Introduction

The ability to easily store and retrieve digitized documents is an important feature of any document management workflow process. In this article, we will illustrate how to use document scan features in an ASP.NET web application to save scanned files as PDFs to an SQL Server database. We’ll also cover retrieval of image files and their display within your ASP.NET web page.

We will be using Dynamic Web TWAIN, which is a TWAIN ActiveX/Plug-in for web applications, to expedite the development of document scanning, uploading and display capabilities.

Key Features

First, it's important to point out key features within Dynamic Web TWAIN that streamlines the development process:

  • Compatible with the mainstream browsers including IE, Firefox, Chrome, Safari and Opera on Windows & Mac OS X
  • Capable of scanning images from scanners and other TWAIN compatible devices
  • Support for BMP, JPEG, PNG, single/multi-page PDF and single/multi-page TIFF
  • Support for HTTPS uploading
  • Support for cookies & sessions
  • Support for uploading extra text alongside respective images

Using the Code

Document Scanning

As Dynamic Web TWAIN is a client-side SDK, we will use JavaScript to call its methods/properties. With the SDK, you can customize the scan settings such as resolution, pixel type, brightness, contrast, page size, etc. However, in this article we will focus on aspects of storing and retrieving images from SQL Server. To this end, we will only cover a simple scan process.

C#
function acquireImage() {
    if (_divDWTSourceContainerID == "")
        DWObject.SelectSource();
    else
        DWObject.SelectSourceByIndex(document.getElementById(_divDWTSourceContainerID).selectedIndex); //select a TWAIN scanner
    DWObject.CloseSource(); //make sure the source is closed before using it
    DWObject.OpenSource();
    DWObject.IfShowUI = document.getElementById("ShowUI").checked; //show or hide the user interface of the TWAIN scanner

    var i;
    for (i = 0; i < 3; i++) {
        if (document.getElementsByName("PixelType").item(i).checked == true)
            DWObject.PixelType = i;
    } // set the pixel type of the acquired images, B/W, gray or color
    DWObject.Resolution = document.getElementById("Resolution").value; //set the resolution
    DWObject.IfFeederEnabled = document.getElementById("ADF").checked; //scan images from auto feeder
    DWObject.IfDuplexEnabled = document.getElementById("Duplex").checked; //enable duplex scanning
    appendMessage("Pixel Type: " + DWObject.PixelType + "<br />Resolution: " + DWObject.Resolution + "<br />");

    DWObject.IfDisableSourceAfterAcquire = true;
    DWObject.AcquireImage(); //start document scanning
}

Save Scanned Images as a Multi-Page PDF to SQL Server

After scanning you can save images in many file formats: BMP, PNG, JPG, TIF and PDF. Multi-page TIF and PDF are also supported. In this example, we will save the images as a multi-page PDF file. The respective code is as follows:

C#
        function btnUpload_onclick() {
    if (!checkIfImagesInBuffer()) {
        return;
    }
    var i, strHTTPServer, strActionPage, strImageType;
    _txtFileName.className = "";
    if (!strre.test(_txtFileName.value)) {
        _txtFileName.className += " invalid";
        _txtFileName.focus();
        appendMessage("Please input file name.<br />Currently only English names are allowed.<br />");
        return;
    }
    //DWObject.MaxInternetTransferThreads = 5;
    strHTTPServer = _strServerName;
    DWObject.HTTPPort = _strPort;
    var CurrentPathName = unescape(location.pathname); // get current PathName in plain ASCII	
    var CurrentPath = CurrentPathName.substring(0, CurrentPathName.lastIndexOf("/") + 1);
    strActionPage = CurrentPath + _strActionPage; // the aspx page for receiving image data on the server side
    var redirectURLifOK = CurrentPath + "online_demo_list.aspx";  
    var uploadfilename = _txtFileName.value + "." + document.getElementsByName("ImageType").item(i).value;

    DWObject.HTTPUploadAllThroughPostAsPDF(
            strHTTPServer,
            strActionPage,
            uploadfilename
        ); //upload images as multi-page PDF file

    _strTempStr = _strTempStr + "Upload: ";
    if (checkErrorString()) {
        if (strActionPage.indexOf("SaveToFile") != -1)
            alert(DWObject.ErrorString)//if save to file.
        else
            window.location = redirectURLifOK;
    }
}

Action Page - SaveToDB.aspx

This action page is used for receiving the image data posted from the scan page.

<%@ Page Language="C#"%>
<%
try
{
    String strImageName;
    int iFileLength;
    HttpFileCollection files = HttpContext.Current.Request.Files;
    HttpPostedFile uploadfile = files["RemoteFile"];
    strImageName = uploadfile.FileName;
    iFileLength = uploadfile.ContentLength;

    Byte[] inputBuffer = new Byte[iFileLength];
    System.IO.Stream inputStream;

    inputStream = uploadfile.InputStream;
    inputStream.Read(inputBuffer, 0, iFileLength);

    String strConnString;

    strConnString = Common.DW_ConnString;

    System.Data.SqlClient.SqlConnection sqlConnection = new System.Data.SqlClient.SqlConnection(strConnString);

    String SqlCmdText = "INSERT INTO " + Common.DW_SaveTable + " (strImageName,imgImageData) VALUES (@ImageName,@Image)";
    System.Data.SqlClient.SqlCommand sqlCmdObj = new System.Data.SqlClient.SqlCommand(SqlCmdText, sqlConnection);

    sqlCmdObj.Parameters.Add("@Image", System.Data.SqlDbType.Binary, iFileLength).Value = inputBuffer;
    sqlCmdObj.Parameters.Add("@ImageName", System.Data.SqlDbType.VarChar, 255).Value = strImageName;

    sqlConnection.Open();
    sqlCmdObj.ExecuteNonQuery();
    sqlConnection.Close();
}
catch
{
} 
%>

Retrieving the PDF File from the Database for Display on a Web Page

Online_demo_view.aspx for displaying the PDF file

C#
setTimeout(function () {
    var CurrentPathName = unescape(location.pathname);  // get current PathName in plain ASCII
    var CurrentPath = CurrentPathName.substring(0, CurrentPathName.lastIndexOf("/") + 1);
    var strActionPage = CurrentPath + "online_demo_download.aspx"; //the ActionPage's file path

    strHTTPServer = location.hostname;
    DWObject.HTTPPort = location.port==""?80:location.port;
    var downloadsource = strActionPage +
       "?iImageIndex=<%=strImageID%>&ImageName=<%=strImageName%>&ImageExtName=<%=strImageExtName%>";
    DWObject.HTTPDownloadEx(strHTTPServer, downloadsource,<%=strImageFileType %>);
}, 500);

online_demo_download.aspx is for retrieving image from the database

<%@ Page Language="C#"%>

<%
	String strExc = "";
    try
    {
        //Get the image data from the database
        HttpRequest request = HttpContext.Current.Request;

        String strImageName;
        String strImageExtName;
        String strImageID;

        strImageName = request["ImageName"];
        strImageExtName = request["ImageExtName"];
        strImageID = request["iImageIndex"];

        String strConnString;

        strConnString = Common.DW_ConnString;

        System.Data.SqlClient.SqlConnection sqlConnection = new System.Data.SqlClient.SqlConnection(strConnString);
        System.Data.SqlClient.SqlCommand sqlCmdObj = new System.Data.SqlClient.SqlCommand("SELECT imgImageData FROM " + 
            Common.DW_SaveTable + " WHERE iImageID= " + strImageID, sqlConnection);

        sqlConnection.Open();

        System.Data.SqlClient.SqlDataReader sdrRecordset = sqlCmdObj.ExecuteReader();

        sdrRecordset.Read();

        long iByteLength;
        iByteLength = sdrRecordset.GetBytes(0, 0, null, 0, int.MaxValue);

        byte[] byFileData = new byte[iByteLength];

        sdrRecordset.GetBytes(0, 0, byFileData, 0, Convert.ToInt32(iByteLength));

        sdrRecordset.Close();
        sqlConnection.Close();

        sdrRecordset = null;
        sqlConnection = null;

        Response.Clear();
        Response.Buffer = true;

        if (strImageExtName == "bmp")
        {
            Response.ContentType = "image/bmp";
        }
        else if (strImageExtName == "jpg")
        {
            Response.ContentType = "image/jpg";
        }
        else if (strImageExtName == "tif")
        {
            Response.ContentType = "image/tiff";
        }
        else if (strImageExtName == "png")
        {
            Response.ContentType = "image/png";
        }
        else if (strImageExtName == "pdf")
        {
            Response.ContentType = "application/pdf";
        }

        try
        {
            String fileNameEncode;
            fileNameEncode = HttpUtility.UrlEncode(strImageName, System.Text.Encoding.UTF8);
            fileNameEncode = fileNameEncode.Replace("+", "%20");
            String appendedheader = "attachment;filename=" + fileNameEncode;
            Response.AppendHeader("Content-Disposition", appendedheader);

            Response.OutputStream.Write(byFileData, 0, byFileData.Length);
        }
        catch (Exception exc)
        {
            strExc = exc.ToString();
            DateTime d1 = DateTime.Now;
            string logfilename = d1.Year.ToString() + d1.Month.ToString() + d1.Day.ToString() + 
               d1.Hour.ToString() + d1.Minute.ToString() + d1.Second.ToString() + "log.txt";
            String strField1Path = HttpContext.Current.Request.MapPath(".") + "/" + logfilename;
            if (strField1Path != null)
            {
                System.IO.StreamWriter sw1 = System.IO.File.CreateText(strField1Path);
                sw1.Write(strExc);
                sw1.Close();
            }
            Response.Flush();
            Response.Close();
        }
    }
    catch (Exception ex)
    {
        strExc = ex.ToString();
        DateTime d1 = DateTime.Now;
        string logfilename = d1.Year.ToString() + d1.Month.ToString() + d1.Day.ToString() + 
            d1.Hour.ToString() + d1.Minute.ToString() + d1.Second.ToString() + "log.txt";
        String strField1Path = HttpContext.Current.Request.MapPath(".") + "/" + logfilename;
        if (strField1Path != null)
        {
            System.IO.StreamWriter sw1 = System.IO.File.CreateText(strField1Path);
            sw1.Write(strExc);
            sw1.Close();
        }
        Response.Write(strExc);
    } 
%>

Deploy & Run the Application

The complete source code can be downloaded from the article.

You can use the 'Create Table.sql' to set up the database to store the scanned images for the demo application. Please update the value of DW_ConnString for your SQL Server connection info in App_Code\Common.cs before running.

To customize the source code according to your requirements, you can download Dynamic Web TWAIN from Dynamsoft's website.
Dynamic Web TWAIN 30-Day Free Trial Download

To test the document imaging features from different client machines, you can simply copy the sample code to your web server (IIS, Apache or Tomcat). Users will only need to download and install the ActiveX/Plugin in for their browser on the first visit of the web page. 

The online demo is also available for your reference.
Dynamic Web TWAIN Online Demo

Support

Is your organization currently undergoing a document management project? Have you deployed Dynamsoft's SDK? If so, how has it helped? Let us know in the comments section or by contacting us. You can also contact us if you need any help to get this sample code up and running. To do so, reach us by email at support@dynamsoft.com. For pricing or licensing questions, call us at 1-877-605-5491 or email our sales team at sales@dynamsoft.com.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Canada Canada
Dynamsoft has more than 15 years of experience in TWAIN SDKs, imaging SDKs and version control solutions.

Our products include:

TWAIN SDK
- Dynamic Web TWAIN: a TWAIN scanning SDK optimized for web document management applications.
- Dynamic .NET TWAIN: a .NET TWAIN and Directshow Image Capture SDK for WinForms/WPF applications.

Imaging SDKs
- Barcode Reader for Windows, Linux, macOS, iOS, Android and Raspberry Pi.
- OCR addon for both web and .NET TWAIN SDKs

Version Control
- SourceAnywhere: a SQL server-based source control solution. Both on-premise and hosting options are provided.

http://www.dynamsoft.com/
This is a Organisation

21 members

Comments and Discussions

 
-- There are no messages in this forum --