-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
74 lines (69 loc) · 2.39 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
64
65
66
67
68
69
70
71
72
73
74
var express = require('express')
var fs = require('fs')
var multiparty = require('multiparty')
var config = require(process.argv[2] || './config')
var http = require('http')
var app = express()
var uuid = require('node-uuid').v4
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", req.headers['origin'])
res.header("Access-Control-Allow-Credentials", true)
res.header("Access-Control-Allow-Headers", req.headers['access-control-request-headers'])
res.header("Access-Control-Allow-Methods",req.headers['access-control-request-method'])
res.header("X-Powered-By",' 3.2.1')
res.header("Content-Type", "application/json;charset=utf-8")
next()
})
app.get('/file/:file', function(req, res) {
var filename = req.params.file
var filepath = config.uploadDir + filename
res.header("Content-Type", "image/png")
res.sendFile(config.uploadDir + filename)
})
function validToken(req) {
if (config.Authorization) {
return new Promise(function(resolve, reject) {
var api = config.Authorization.api + req.header(config.Authorization.headerName)
http.get(api, response => {
if (response.statusCode === 200) {
resolve()
}
}).on('error', (e) => {
reject(e)
})
});
}
return Promise.resolve()
}
app.post('/upload', function (req, res){
validToken(req).then(() => {
var form = new multiparty.Form({uploadDir: config.uploadDir});
form.on('error', function(err) {
console.log('Error parsing form: ' + err.stack)
res.send({success: false, msg: err.toString()})
});
form.parse(req, function (err, fields, files){
if (err){
res.send({success: false, msg: err.toString()})
} else {
var fileDataArr = files['file']
console.log('file-upload-request', fileDataArr)
if (fileDataArr) {
var fileData = fileDataArr[0]
var oldName = fileData.path
var suffix = oldName.substr(oldName.lastIndexOf('.')) || '.png'
var newName = uuid() + suffix
fs.rename(oldName, config.uploadDir + newName)
res.send(config.downDomain + newName)
} else {
console.log('file-upload-faild')
res.sendStatus(500, fileDataArr)
}
}
})
}).catch(() => {
res.sendStatus(403)
})
})
app.listen(config.port)
console.log('listen on port:', config)