-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathserver.js
97 lines (85 loc) · 3.41 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
var formidable = require('formidable');
var util = require('util');
var express = require('express');
var fs = require('fs');
var app = express();
var path = require('path');
var http = require('http');
var dbr = require('../../index.js');
// Get a license key from https://www.dynamsoft.com/customer/license/trialLicense/?product=dcv&package=cross-platform
dbr.initLicense("DLS2eyJoYW5kc2hha2VDb2RlIjoiMjAwMDAxLTE2NDk4Mjk3OTI2MzUiLCJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSIsInNlc3Npb25QYXNzd29yZCI6IndTcGR6Vm05WDJrcEQ5YUoifQ==");
var barcodeTypes = dbr.barcodeTypes;
function decodeBarcode(res, fileName, barcodeType) {
// read barcode using dbr
dbr.decodeFileAsync(fileName, barcodeType, function (err, msg) {
var response = 'Totol count: ' + msg.length;
var result = null;
for (let index in msg) {
result = msg[index]
response += '<p>' + result['format'] + ': ';
response += result['value'] + '<p>';
}
res.send(response);
}, "");
}
app.use(express.static(__dirname));
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();
});
app.post('/upload', function (req, res) {
var form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
var dir = 'uploads';
fs.mkdir(dir, function (err) {
var flag = fields.uploadFlag;
var barcodeType = parseInt(fields.barcodetype);
console.log('flag: ' + flag);
if (flag === '1') {
// read barcode image file
fs
.readFile(files.fileToUpload.path, function (err, data) {
// save file from temp dir to new dir
var fileName = path.join(__dirname, dir, files.fileToUpload.name);
console.log(fileName);
fs.writeFile(fileName, data, function (err) {
if (err)
throw err;
decodeBarcode(res, fileName, barcodeType);
});
});
} else { // read barcode image url
var tmpFileName = path.join(__dirname, dir, 'tmp.jpg');
var tmp = fs.createWriteStream(tmpFileName);
var url = fields.fileToDownload;
console.log('url: ' + url);
try {
http.get(url, function (response) {
response.pipe(tmp);
tmp.on('finish', function () {
tmp
.close(function () {
decodeBarcode(res, tmpFileName, barcodeType);
});
});
});
} catch (error) {
console.log(error);
res.send('Invalid image!');
}
}
});
});
});
var server = app.listen(2024, function () {
var host = server
.address()
.address;
var port = server
.address()
.port;
console.log('listening at http://localhost:%s', port);
});