-
Notifications
You must be signed in to change notification settings - Fork 0
/
filesController.js
79 lines (61 loc) · 2.03 KB
/
filesController.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
var utils = require('./utilities.js');
var uploads = [];
var idCount = 0;
var filesController = function filesController(activityLog) {
this.upload = function (request, response) {
var filename = request.headers['x-filename'];
var contentLength = request.headers['content-length'];
var alias = request.headers['x-alias'];
if (utils.isAvailable([ filename, contentLength, alias ]) == false) {
utils.statusResponse(400, response);
return;
}
var upload = {
id: idCount++,
name: filename,
contentLength: contentLength,
data: []
};
var fileIsImage = isImage(filename);
var entry = {
type: fileIsImage ? 'image' : 'file',
alias: alias,
name: filename,
path: '/download/' + upload.id,
fileId: upload.id
};
request.on('data', function (chunk) {
upload.data.push(chunk);
});
request.on('end', function () {
uploads.push(upload);
activityLog.addEntry(entry);
utils.emptyResponse(response);
});
};
var isImage = function (filename) {
return filename.match(/\.(jpg|gif|png|bmp|jpeg)$/i);
};
this.download = function (request, response) {
var id = request.params.id;
if (utils.isAvailable([ id ]) == false) {
utils.statusResponse(400, response);
return;
}
var upload = uploads[id];
if (!upload) {
response.writeHead(404);
response.end('Cannot get /download/' + id);
return;
}
var headers = {
'Content-Length': upload.contentLength,
'Content-Disposition': 'inline; filename="' + upload.name + '"'
};
response.writeHead(200, headers);
for (i = 0; i < upload.data.length; i++)
response.write(upload.data[i]);
response.end();
};
};
module.exports = filesController;