Upload images/documents to the web server

Preparation

Before we upload the image(s), we need to define the path for the action page. An action page is used to receive the image data and handle all the server-side operation such as saving the data on the hard disk or in a database, etc.
Here is an example:

var strHttpServer = location.protocol + '//' +
			location.hostname + 
			(location.port === '' ? '' : ':' + location.port);
var currentPathName = unescape(location.pathname);
var currentPath = currentPathName.substring(0, currentPathName.lastIndexOf('/') + 1);
var currentPagePath = strHttpServer + currentPath;
var actionPageUrl = currentPagePath + 'ActionPage.aspx';  

strHTTPServer is used to store the server name/IP which specifies which server the image(s) will be uploaded to as well as the port number. 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.

Normally, port 80 is for HTTP, port 443 is for HTTPS. If you are not sure about the port number, it’s recommended that you 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.
actionPageUrl stores the absolute path of the action page.

NOTE:

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 one HTTP Response Header, namely:

Access-Control-Allow-Origin: *
// the asterisk wild-card permits scripts hosted on any site to load your resources

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.

Calling the methods

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

Format Method
BMP, PNG, JPEG, PDF, TIFF httpUpload()
httpUploadAsync()

If you want to upload images synchronously, you can use httpUpload().
If you want to upload images asynchronously, you can use httpUploadAsync().

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

imageViewer.io.httpUploadAsync(
       actionPageUrl,
       [0,1],
       imageViewer.io.EnumImageType.PDF,
	      onHttpUploadSuccess, onHttpUploadFailure
);

With this method, the first and second images in the Dynamsoft image viewer will be sent to the web server as one multi-page PDF file.
In the above code, the parameters onHttpUploadSuccess and onHttpUploadFailure are callback functions.
The following is a simple implementation of these two functions:

function onHttpUploadSuccess(){ 
    console.log('successful'); 
}
function onHttpUploadFailure(errorCode, errorString, httpResponse){
alert(errorString + httpResponse); 
}

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 (C#, VB, PHP, Java, etc...).

Here is an example in C#:

This action page retrieves the image data from the current 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 you don’t specify the file name, we use timestamp (milliseconds since January 1, 1970) to name it by default. For example: 1477658922059.png, the exact time is 2016-10-28 20:48:42. There are two ways to specify file names, one is specifying it in the first parameter url like http://localhost:1894/ImageUpload/ActionPage.aspx?fileName=”test.pdf”. The other is using method setHTTPFormFields.

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);

Uploading image(s) to a Database

Dynamsoft Camera SDK doesn't save/upload the image(s) to your database directly. Instead, we can upload the image data to the action page first and then use the action page to store the image data in the database.

If you are not sure how to upload the image data to the server, please refer to the previous section Uploading image(s) to the web server.

Different database systems have different data types for image data. We normally use BLOB or varbinary in SQL Server, Long raw or BLOB in Oracle, BLOB in MySQL, etc.

Here is an example in C# with SQL 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();

We get the file object from the current request and write the image data to the 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".

Uploading image(s) with extra data

If you are not sure how to upload the image data to the server, please refer to the previous topic "Upload images/documents to the web server".

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 setHTTPFormFields.

setHTTPFormFields(iVaule)

iValue is expressed in JSON format:{"fieldName": "fieldValue", "fieldName": "fieldValue",...}

  • string fieldName: specifies the name of a text field in the web form.
  • string fieldValue: specifies the value of a text field in the web form.

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

imageViewer.io.setHTTPFormFields({'EmployeeID': '2012000054', 'DocumentType': 'Invoice'}); 

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'];
Is this page helpful?

Leave a Reply

Your email address will not be published.