-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
63 lines (51 loc) · 1.55 KB
/
index.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
const sharp = require('sharp');
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const multer = require('multer');
const storage = multer.memoryStorage()
const upload = multer({ storage: storage })
const app = express();
app.listen(3005);
app.use(cors());
app.use(bodyParser.json());
const imageProcessor = (processingPromise, options) => {
if (options.rotate) {
processingPromise = processingPromise
.rotate(Number(options.rotate));
}
if (options.width) {
processingPromise = processingPromise
.resize({width: Number(options.width)});
}
if (options.png) {
processingPromise = processingPromise
.png();
}
if (options.jpeg) {
processingPromise = processingPromise
.jpeg();
}
return processingPromise;
}
app.post('/', upload.single('file'), async (req, res) => {
try {
let processingPromise = sharp(req.file.buffer);
const processorOptions = JSON.parse(req.body.processorOptions);
const options = JSON.parse(req.body.options);
if (processorOptions.type === 'image') {
processingPromise = imageProcessor(processingPromise, options);
}
const data = await processingPromise
.toBuffer();
res.writeHead(200, {
'Content-Type': req.file.mimetype,
'Content-disposition': 'attachment;filename=' + req.file.originalname,
'Content-Length': data.length
});
res.end(Buffer.from(data, 'binary'));
}
catch (err) {
res.status(400).send('File processing has been failed. ' + err.message);
}
});