forked from NicolasRitouet/dpd-fileupload
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
274 lines (234 loc) · 9.06 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
"use strict";
/**
* Module dependencies
*/
var Resource = require('deployd/lib/resource'),
util = require('util'),
debug = require('debug')('dpd-fileupload'),
formidable = require('formidable'),
fs = require('fs'),
md5 = require('MD5'),
gm = require('gm'),
mime = require('mime');
/**
* Module setup.
*/
function Fileupload(options) {
Resource.apply(this, arguments);
this.store = process.server.createStore(this.name + "fileupload");
this.config = {
directory: this.config.directory || 'upload',
sizes: this.config.sizes.split(',') || ['200x200'],
fullDirectory: __dirname + "/../../public/" + (this.config.directory || 'upload') + "/",
uploadPath: "./public/" + (this.config.directory || 'upload') + "/"
};
if (this.name === this.config.directory) {
this.config.directory = this.config.directory + "_";
}
// If the directory doesn't exists, we'll create it
try {
fs.statSync(this.config.fullDirectory).isDirectory();
} catch (er) {
fs.mkdir(this.config.fullDirectory);
}
}
util.inherits(Fileupload, Resource);
Fileupload.label = "File upload";
Fileupload.events = ["get", "upload", "delete"];
Fileupload.prototype.clientGeneration = true;
Fileupload.basicDashboard = {
settings: [
{
name: 'directory',
type: 'text',
description: 'Directory to save the uploaded files. Defaults to \'upload\'.'
},
{
name: 'sizes',
type: 'text',
description: 'Comma separated thumb sizes. Default to 200x200'
}
]
};
/**
* Module methods
*/
Fileupload.prototype.handle = function (ctx, next) {
var req = ctx.req,
self = this,
domain = {url: ctx.url};
if (req.method === "POST" || req.method === "PUT") {
var form = new formidable.IncomingForm(),
uploadDir = this.config.fullDirectory,
resultFiles = [],
remainingFile = 0,
storedObject = {},
uniqueFilename = false,
sizes = this.config.sizes,
subdir,
creator;
// Will send the response if all files have been processed
var processDone = function(err, file) {
if (err) {
fs.unlink(file.path, function(err) {});
return ctx.done(err);
}
remainingFile--;
if (remainingFile === 0) {
debug("Response sent: ", resultFiles);
return ctx.done(null, resultFiles);
}
}
// If we received params from the request
if (typeof req.query !== 'undefined') {
for (var propertyName in req.query) {
debug("Query param found: { %j:%j } ", propertyName, req.query[propertyName]);
if (propertyName === 'subdir') {
debug("Subdir found: %j", req.query[propertyName]);
uploadDir = uploadDir.concat(req.query[propertyName]).concat("/");
// If the sub-directory doesn't exists, we'll create it
try {
fs.statSync(uploadDir).isDirectory();
} catch (er) {
fs.mkdir(uploadDir);
}
} else if (propertyName === 'uniqueFilename') {
debug("uniqueFilename found: %j", req.query[propertyName]);
uniqueFilename = (req.query[propertyName] === 'true');
continue; // skip to the next param since we don't need to store this value
}
// Store any param in the object
try {
storedObject[propertyName] = JSON.parse(req.query[propertyName]);
} catch (e) {
storedObject[propertyName] = req.query[propertyName];
}
}
}
form.uploadDir = uploadDir;
var renameAndStore = function(file) {
fs.rename(file.path, uploadDir + file.name, function(err) {
if (err) return processDone(err);
debug("File renamed after event.upload.run: %j", err || uploadDir + file.name);
storedObject.filename = file.name;
if (uniqueFilename) {
storedObject.originalFilename = file.originalFilename;
}
storedObject.filesize = file.size;
storedObject.creationDate = new Date().getTime();
// Store MIME type in object
storedObject.mimeType = mime.lookup(file.name);
//Resize
sizes.forEach(function(size){
var imgDir = file.path.replace(file.path.split('/').pop(),'');
try {
fs.statSync(imgDir+size).isDirectory();
} catch (er) {
fs.mkdir(imgDir+size);
}
try {
var imgSize = size.split('x');
var imgExt = file.name.split('.').pop();
var imgName = file.name.replace(imgExt,'');
gm(imgDir+imgName+imgExt)
.resize(imgSize[0], imgSize[1])
.noProfile()
.write(imgDir+size+'/'+imgName+imgExt, function (err) {
if (err) console.log(err);
if (!err) console.log('done');
});
} catch (err){}
});
self.store.insert(storedObject, function(err, result) {
if (err) return processDone(err);
debug('stored after event.upload.run %j', err || result || 'none');
resultFiles.push(result);
processDone();
});
});
}
form.parse(req)
.on('file', function(name, file) {
debug("File %j received", file.name);
if (uniqueFilename) {
file.originalFilename = file.name;
file.name = md5(Date.now()) + '.' + file.name.split('.').pop();
}
if (self.events.upload) {
self.events.upload.run(ctx, {url: ctx.url, filesize: file.size, filename: file.name.split('.')[0], type: file.type, path: file.path.replace(file.path.split('/').pop(),''), ext: '.' + file.name.split('.').pop(), sizes: sizes }, function(err) {
if (err) return processDone(err, file);
renameAndStore(file);
});
} else {
renameAndStore(file);
}
}).on('fileBegin', function(name, file) {
remainingFile++;
debug("Receiving a file: %j", file.name);
}).on('error', function(err) {
debug("Error: %j", err);
return processDone(err);
});
return req.resume();
} else if (req.method === "GET") {
if (this.events.get) {
this.events.get.run(ctx, domain, function(err) {
if (err) return ctx.done(err);
self.get(ctx, next);
});
} else {
this.get(ctx, next);
}
} else if (req.method === "DELETE") {
if (this.events['delete']) {
this.events['delete'].run(ctx, domain, function(err) {
if (err) return ctx.done(err);
self.del(ctx, next);
});
} else {
this.del(ctx, next);
}
} else {
next();
}
};
Fileupload.prototype.get = function(ctx, next) {
var self = this,
req = ctx.req;
if (!ctx.query.id) {
self.store.find(ctx.query, function(err, result) {
ctx.done(err, result);
});
}
};
// Delete a file
Fileupload.prototype.del = function(ctx, next) {
var self = this,
fileId = ctx.url.split('/')[1],
uploadDir = this.config.fullDirectory,
sizes = this.config.sizes;
this.store.find({id: fileId}, function(err, result) {
if (err) return ctx.done(err);
debug('found %j', err || result || 'none');
if (typeof result !== 'undefined') {
var subdir = "";
if (result.subdir !== null) {
subdir = result.subdir;
}
self.store.remove({id: fileId}, function(err) {
if (err) return ctx.done(err);
fs.unlink(uploadDir + subdir + "/" + result.filename, function(err) {
if (err) return ctx.done(err);
sizes.forEach(function(size){
fs.unlink(uploadDir + subdir + "/"+ size + "/" + result.filename, function(err) {});
});
ctx.done(null, {statusCode: 200, message: "File " + result.filename + " successfuly deleted"});
});
});
}
});
};
/**
* Module export
*/
module.exports = Fileupload;