Upload image(s) to the web server

NOTE

Before we upload the image(s), we need to set the server IP/name, set the port number, as well as define the path for the action page. The action page refers to the target script that receives the HTTP Post request containing the image data and handles all the server-side operation like saving the data on the hard disk or database, etc. Here is an example:

Upload and Save on the Server Disk

var strHTTPServer = location.hostname;
DWObject.HTTPPort = location.port == "" ? 80 : location.port;
var CurrentPathName = unescape(location.pathname);
var CurrentPath = CurrentPathName.substring(0, CurrentPathName.lastIndexOf("/") + 1);
var strActionPage = CurrentPath + "actionPage.aspx";
var uploadfilename = "TestImage.pdf";

In the code snippet

strHTTPServer is used to store the server name which specifies which server the image(s) will be uploaded to. You can also use the server’s IP for the same purpose. If you want to upload image(s) to the same server as the current page, we suggest you use location.hostname to get the hostname at runtime.

The property HTTPPort specifies the HTTP port to be used for the upload. Normally, port 80 is for HTTP, port 443 is for HTTPS. If you are not sure about the port number, you can use location.port == "" ? 80 : location.port to get the current port number at runtime.

CurrentPathName and CurrentPath are used to build the relative path of the action page.

strActionPage stores the relative path of the action page.

uploadfilename stores the file name for the uploaded image(s). You should change the extension of the name accordingly.

NOTE

In version 10.0 and above, we are using the browser as the upload agent. Due to browser security restrictions, client-side scripts (e.g., JavaScript) are not allowed to make requests to another domain. Therefore, when you try to upload an image to a server with a different domain, subdomain, port, or protocol, you need to configure your server to allow such requests by adding an HTTP Response Header, namely

Access-Control-Allow-Origin: *

Take IIS 7 for example. What you need to do is merge the following lines into the web.config file at the root of your application / site:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Methods" value="OPTIONS,POST,GET,PUT"/>
        <add name="Access-Control-Allow-Headers" value="x-requested-with"/>
        <add name="Access-Control-Allow-Credentials" value="true" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>
</configuration>

If you don't have a web.config file already, just create a new file called "web.config" and add the snippet above.

Methods

Now, we can call one of the HTTP upload methods to upload the image(s). We have 8 methods:

Format Method
Any Type HTTPUploadThroughPostDirectly()
Supported Images HTTPUpload()
HTTPUploadThroughPost()
HTTPUploadThroughPostEx()
Multi-Page PDF HTTPUploadAllThroughPostAsPDF()
HTTPUploadThroughPostAsMultiPagePDF()
Multi-Page TIFF HTTPUploadAllThroughPostAsMultiPageTIFF()
HTTPUploadThroughPostAsMultiPageTIFF()

Let’s take the method HTTPUploadAllThroughPostAsPDF() for example:

DWObject.HTTPUploadAllThroughPostAsPDF(
    strHTTPServer,
    strActionPage,
    uploadfilename,
    OnHttpUploadSuccess,
    OnHttpUploadFailure
);

With this method, all the images in the Dynamic Web TWAIN control will be sent to the web server as one multi-page PDF file.

In the above code, the parameters OnHttpUploadSuccess and OnHttpUploadFailure are optional callback functions. If they are present, the method is asynchronous; otherwise, the method is synchronous. You can use the methods asynchronously to avoid possible browser hanging.

The following is a simple implementation of these two functions:

function OnHttpUploadSuccess() {
    console.log('successful');
}
function OnHttpUploadFailure(errorCode, errorString, sHttpResponse) {
    alert(errorString + sHttpResponse);
}

If you want to upload one image as a single-page file, you can use HTTPUploadThroughPost() or HTTPUploadThroughPostEx().

If you want to upload selected images as a multi-page file, you can use HTTPUploadThroughPostAsMultiPagePDF() or HTTPUploadThroughPostAsMultiPageTIFF().

Action Page

The HTTP upload method(s) makes a standard HTTP post request to the action page on the server. The request contains the image data, image name, etc. In the action page, you can process the image data according to your requirements. Technically you can write the action page in any server-side language (such as C#, VB, PHP, Java).

Here is an example in C#:

This action page retrieves the image data from the current HTTP request object and saves it as a local file on the server.

HttpFileCollection files = HttpContext.Current.Request.Files;
HttpPostedFile uploadfile = files["RemoteFile"];
uploadfile.SaveAs(System.Web.HttpContext.Current.Request.MapPath(".") + "/" + uploadfile.FileName);

Note

Please note that RemoteFile is the default name/key for the uploaded image data. If necessary, you can change it using the property HttpFieldNameOfUploadedImage.

To do the same thing in PHP:

$fileTempName = $_FILES['RemoteFile']['tmp_name'];  
$fileSize = $_FILES['RemoteFile']['size'];
$fileName = $_FILES['RemoteFile']['name']; 
move_uploaded_file($fileTempName, $fileName) ;

Upload to FTP

Besides the HTTP upload methods, you can also use the FTP Upload methods to update the image(s) to your FTP web server. The available APIs are:

Format Method
Any Type FTPUploadDirectly()
Supported Images FTPUpload()
FTPUploadEx()
Multi-Page PDF FTPUploadAllAsPDF()
FTPUploadAsMultiPagePDF()
Multi-Page TIFF FTPUploadAllAsMultiPageTIFF()
FTPUploadAsMultiPageTIFF()

Code Snippet

DWObject.FTPUserName = 'test';
DWObject.FTPPort = 21;
DWObject.FTPPassword = 'test';
DWObject.FTPUploadAllAsPDF(
    '192.168.8.222',
    'test.pdf',
    OnFtpUploadSuccess,
    OnFtpUploadFailure
);

Upload image(s) to a Database

Dynamic Web TWAIN doesn’t save/upload the image(s) to your database directly. Instead, the image data hits the action page first, and then the code in the action page decides where to store it.

If you are not sure how to upload the image data to the server, please refer to the previous section Upload and Save on the Server Disk.

Different database systems may have different data types for image data. We generally use BLOB or varbinary in MSSQL Server, Long raw or BLOB in Oracle, BLOB in MySQL.

Here is an example in C# with MSSQL Server:

int iFileLength;
HttpFileCollection files = HttpContext.Current.Request.Files;
HttpPostedFile uploadfile = files["RemoteFile"];
String strImageName = uploadfile.FileName;

iFileLength = uploadfile.ContentLength;
Byte[] inputBuffer = new Byte[iFileLength];
System.IO.Stream inputStream;
inputStream = uploadfile.InputStream;
inputStream.Read(inputBuffer,0,iFileLength);

// add code to connect to database
String SqlCmdText = "INSERT INTO tblImage (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();

In the code snippet, we get the file object from the current HTTP request and write the image data to a byte array. In the SQL statement, we pass the byte array to the database as System.Data.SqlDbType.Binary and store the data in a BL field called imgImageData.

Upload image(s) with extra data

If you are not sure how to upload the image data to the server, please refer to the previous section Upload and Save on the Server Disk.

Sometimes we need to pass more information to the server. For example, document type, employee ID, document description, etc. Since we don’t have any options to pass extra data in the HTTP upload method, we need to use a method called SetHTTPFormField.

SetHTTPFormField(String sFieldName, String sFieldValue)
  • String sFieldName: specifies the name of a text field in the web form
  • String sFieldValue: specifies the value of a text field in the web form

We need to use this method before the Upload. Here is an example:

DWObject.ClearAllHTTPFormField(); // Clear all fields first
DWObject.SetHTTPFormField("EmployeeID", "2012000054");
DWObject.SetHTTPFormField("DocumentType", "Invoice");
DWObject.SetHTTPFormField("DocumentDesc", "This is an invoice from ...");

In the action page, you can retrieve the data from the request object by the field names. For example:

String EmployeeID = HttpContext.Current.Request.Form["EmployeeID"];

results matching ""

    No results matching ""

    results matching ""

      No results matching ""