經過Dynamic Web TWAIN SDK和Node.js的組合,只須要幾行代碼就能夠實如今瀏覽器中控制掃描儀,獲取圖像後上傳到遠程服務器。css
原文:Document Imaging and Uploading With Dynamic Web TWAIN and Node.jshtml
建立工程目錄,打開cmd.exe進入到工程目錄,安裝下面兩個Node.js模塊:
github
npm install formidable@latest npm install express
建立server.js,初始化:
web
var formidable = require('formidable'); var util = require('util'); var express = require('express'); var fs = require('fs'); var app = express();
把靜態資源,好比圖片,css等,都加載進來:
express
app.use(express.static(__dirname, '/public'));
要實現跨域訪問,須要在header裏添加權限,若是不添加,只能local訪問:npm
app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Methods","PUT, POST, GET, DELETE, OPTIONS"); res.header("Access-Control-Allow-Headers","X-Requested-With, content-type"); res.header("Access-Control-Allow-Credentials", true); next(); });
在POST請求中經過formidable解析數據:
跨域
app.post('/upload', function(req, res) { var form = new formidable.IncomingForm(); form.parse(req, function(err, fields, files) { // console.log(util.inspect({ // fields: fields, // files: files // })); fs.readFile(files.RemoteFile.path, function(err, data) { // save file from temp dir to new dir var newPath = __dirname + "/uploads/" + files.RemoteFile.name; fs.writeFile(newPath, data, function(err) { if (err) throw err; console.log('file saved'); res.end(); }); }); }); })
設置好IP和端口:瀏覽器
var server = app.listen(2014, function() { var host = server.address().address; var port = server.address().port; console.log('listening at http://%s:%s', host, port); })
建立一個網頁,包含一個div和兩個button:
<html> <head> <title>Document Imaging & Uploading</title> <script src="/Resources/dynamsoft.webtwain.initiate.js"></script> <script src="/Resources/dynamsoft.webtwain.config.js"></script> </head> <body> <div id="dwtcontrolContainer"></div> <input type="button" value="Acquire" onclick="AcquireImage();" /> <input id="btnUpload" type="button" value="Upload Image" onclick="btnUpload_onclick()"> </body> </html>
這裏須要把Web TWAIN SDK安裝目錄下的Resources目錄拷貝過來。
加幾行代碼就能夠掃描了:
function AcquireImage(){ DWObject.IfShowUI = false; DWObject.SelectSource(); DWObject.OpenSource(); DWObject.AcquireImage(); }
到這裏能夠先測試下掃描可否正常工做。接下來實現遠程上傳:
function btnUpload_onclick() { DWObject.HTTPPort = 2014; var CurrentPathName = unescape(location.pathname); // get current PathName in plain ASCII var CurrentPath = CurrentPathName.substring(0, CurrentPathName.lastIndexOf("/") + 1); var strActionPage = CurrentPath + "upload"; var strHostIP = "localhost"; // modify the IP for cross-domain access var sFun = function(){ alert('successful'); }, fFun = function(){ alert('failed'); }; DWObject.HTTPUploadThroughPostEx( strHostIP, DWObject.CurrentImageIndexInBuffer, strActionPage, "test.jpg", 1,// JPEG sFun, fFun ); }
測試下。命令行啓動server:
node server.js
打開http://localhost:2014就能夠玩了。
https://github.com/DynamsoftRD/nodejs-dwt
git clone https://github.com/DynamsoftRD/nodejs-dwt.git