Resources Base
Table of contents

Output

Different ways to export data from the DWT buffer.

Upload

The most common usage of DWT is to scan documents and upload them to the server via HTTP and FTP . The library has a number of APIs to make this happen. Read on to learn more.

HTTP with Built-in APIs

For HTTP uploading, Dynamsoft recommends the method HTTPUpload() . Check out the following code snippet

/**
 * Upload the images specified by their indices in the specified file type.
 * @param indices Specify the images
 * @param type Specify the file type
 */
function upload(indices, type) {
    var protocol = Dynamsoft.Lib.detect.ssl ? "https://" : "http://",
        port = window.location.port === "" ? 80 : window.location.port,
        actionPage = "/upload.aspx";
    // path to the server-side script
    var url = protocol + window.location.hostname + ":" + port + actionPage;
    var fileName = "SampleFile" + getExtension(type);
    if (DWObject) {
        DWObject.HTTPUpload(
            url,
            indices,
            type,
            Dynamsoft.DWT.EnumDWT_UploadDataFormat.Binary,
            fileName,
            function() {
                console.log('Success');
            },
            function(errCode, errString, responseStr) {
                console.log(errString);
            }
        );
    }
}
/**
 * Return the extension string of the specified image type.
 * @param type The image type (number).
 */
function getExtension(type) {
    switch (type) {
        case 0:
            return ".bmp";
        case 1:
            return ".jpg";
        case 2:
         return ".tif";
        case 3:
            return ".png";
        case 4:
            return ".pdf";
        case 7:
        case 8:
        default:
            return ".unknown";
    }
}

HTTP with the File Uploader

The File Uploader is an independent component that is dedicated to file uploading. It can be used seamlessly with DWT .

How is upload done using the File Uploader

  1. DWT will prepare the file to upload with the method GenerateURLForUploadData()

Check out how to use the Uploader in the following code snippets

<div id="processbar" style="width:0%;"></div>
// Create a File Uploader instance
Dynamsoft.FileUploader.Init('', function(obj) {
        dsUploadManager = obj;
    },
    function(errCode, errStr) {
        console.log(errStr);
    }
);

function useUploader(indices, type) {
    if (DWObject) {
        DWObject.GenerateURLForUploadData(indices, type, function(url, indices, iImageType) {
            // Create a Job
            var job = dsUploadManager.CreateJob();
            // Configure the Job
            job.ServerUrl = "https://YOUR-SITE:PORT/PATH/TO/SCRIPT.aspx";
            var fileName = "SampleFile" + getExtension(type);
            job.SourceValue.Add(url, fileName);
            job.OnUploadTransferPercentage = function(obj, percentage) {
                var processbar = document.getElementById("processbar");
                processbar.style.width = a + "%";
            };
            job.OnRunSuccess = function() {};
            job.OnRunFailure = function() {};
            // Run the Job
            dsUploadManager.Run(job);
        }, function() {});
    }
}

Check out Server-side Scripting for more information on the target URL.

HTTP with existing upload logic

In some cases, you might already have an upload logic in your application and just want to upload the data in the DWT buffer with the same logic. The following code assumes the existing logic is pure AJAX which expects the FormData

function uploadThroughAJAX(indices, type) {
    DWObject.ConvertToBlob(
        indices,
        type,
        function(result, _indices, type) {
            var url = "https://YOUR-SITE:PORT/PATH/TO/SCRIPT.aspx";
            var fileName = "SampleFile" + getExtension(type);
            var formData = new FormData();
            formData.append('RemoteFile', result, fileName);
            makeRequest(url, formData, false);
        },
        function(errorCode, errorString) {
            console.log(errorString);
        }
    );
}

function makeRequest(url, formData, flg) {
    // Set up the request
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    } else {
        if (window.ActiveXObject) {
            try {
                xhr = new ActiveXObject("MSXML2.XMLHTTP.3.0");
            } catch (ex) {
                alert(ex);
            }
        }
    }
    if (xhr) {
        if (flg) {
            // Open the connection
            xhr.open("GET", url, true);
            xhr.onreadystatechange = requestresult;
            xhr.setRequestHeader("If-Modified-Since", "0");
            xhr.send(null);
        } else {
            // Send the Data via POST
            xhr.open("POST", url, false);
            if (formData != null) {
                xhr.send(formData);
            } else {
                xhr.send(null);
            }
        }
    } else {
        alert("Sorry, but I couldn't create an XMLHttpRequest! ");
    }
}

function requestresult() {
    if (xhr.readyState == 4) {
        if (xhr.status == 200) {
            // File(s) uploaded
            var outMsg;
            if (xhr.responseXML && xhr.responseXML.documentElement) {
                outMsg = xhr.responseXML;
                alert(xhr.responseText);
            }
        }
    }
}

FTP

FTP is a lot simpler than HTTP. A simple example:

DWObject.FTPUserName = 'test';
DWObject.FTPPort = 21;
DWObject.FTPPassword = 'test';
DWObject.FTPUpload(
    '192.168.8.222', //The FTP Host
    0, // The index of the image
    'test.pdf', // The path & name of the file 
    OnFtpUploadSuccess, // Callback in case of success
    OnFtpUploadFailure // Callback in case of failure
);

DWT provides quite a few APIs for FTP upload too

Save

DWT offers several methods to save your images to an absolute file path. Depending on what your exact needs are, you can choose from any of the following methods:

Show dialog to save

Supported on desktop.

You can set the IfShowFileDialog property to true , which will show the open/save file dialog whenever you save an image(s) within the DWT buffer

DWObject.IfShowFileDialog = true;
// The path is selected in the dialog, therefore we only need the file name
DWObject.SaveAllAsPDF("Sample.pdf",
    function() {
        console.log('Successful!');
    },
    function(errCode, errString) {
        console.log(errString);
    }
);

Save to an absolute path

Supported on desktop.

If you don’t want to show any dialog and you know for sure where you want the files saved, you can save with absolute paths while setting IfShowFileDialog to false .

When using an absolute path, you must make sure the current user has the proper permission to save to that path. Otherwise the save will fail.

DWObject.IfShowFileDialog = false;
DWObject.SaveAllAsPDF("D:\\Sample.pdf",
    function() {
        console.log('Successful!');
    },
    function(errCode, errString) {
        console.log(errString);
    }
);

Save as a download

Supported on WASM browsers.

In WASM browsers, DWT runs its entire operations within the browser. So saving locally triggers will instead download the file and IfShowFileDialog will have no effect.

// The following line only works on desktop but it 
// doesn't throw errors on WASM browsers either 
DWObject.IfShowFileDialog = false;
// The following line specifies an absolute path but 
// only the name 'Sample.pdf' is used in WASM browsers
DWObject.SaveAllAsPDF("D:\\Sample.pdf",
    function() {
        console.log('Successful!');
    },
    function(errCode, errString) {
        console.log(errString);
    }
);

Save multiple files to the same location

If you want the user to choose a file path once and then save multiple images to that location, you can do so via the OnGetFilePath event.

DWObject.RegisterEvent("OnGetFilePath", (isSave, filesCount, index, directory, _fn) => {
    if (directory === "" && _fn === "") {
        console.log("User cancelled the operation.")
    } else {
        var path = directory + "\\" + _fn.substr(0, _fn.lastIndexOf("."));
        DWObject.IfShowFileDialog = false;
        for (var i = 1; i < DWObject.HowManyImagesInBuffer; i++) {
            DWObject.SaveAsJPEG(path + "-" + i.toString() + ".jpg", i,
                function() {
                    console.log('Successful!');
                },
                function(errCode, errString) {
                    console.log(errString);
                }
            );
        }
    }
});
DWObject.IfShowFileDialog = true;
DWObject.SaveAsJPEG("Sample.jpg", 0,
    function() {
        console.log('Successful!');
    },
    function(errCode, errString) {
        console.log(errString);
    }
);

Convert

In some cases, you want to process the data yourself and want to extract it from the DWT buffer. DWT offers two approaches.

Convert to a Blob

To do this, use the method ConvertToBlob() which has been mentioned several times above. The following is a simple example

DWObject.ConvertToBlob(
    [0, 1, 2],
    Dynamsoft.DWT.EnumDWT_ImageType.IT_PDF,
    function(result, indices, type) {
        console.log(result.size);
    },
    function(errorCode, errorString) {
        console.log(errorString);
    }
);

Convert to Base64

To do this, use the method ConvertToBase64()

DWObject.ConvertToBase64(
    [0, 1, 2],
    Dynamsoft.DWT.EnumDWT_ImageType.IT_PDF,
    function(result, indices, type) {
        console.log(result.getData(0, result.getLength()));
    },
    function(errorCode, errorString) {
        console.log(errorString);
    }
);

Print

DWT supports printing with the method Print() .

Is this page helpful?

YesYes NoNo

In this article:

latest version

    • Latest Version
    • Version 17.0
    • Version 16.2
    • Version 16.1.1
    Change +
    © 2003–2021 Dynamsoft. All rights reserved.
    Privacy Statement / Site Map / Home / Purchase / Support