forked from shy2850/node-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathupload.js
More file actions
51 lines (51 loc) · 2.1 KB
/
upload.js
File metadata and controls
51 lines (51 loc) · 2.1 KB
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
"use strict";
var mime = require('mime'),
fs = require('fs'),
path = require('path'),
formidable = require('formidable'),
mini = require("./../filter/middleware").mini;
var uploadBase = fs.readFileSync( path.join( __dirname, "/../html/upload.html" ),'utf-8'),
uploadModel = path.join( __dirname, "/../html/uploadOK.html");
exports.execute = function(req, resp, root, handle, conf, modelPath){
var form = new formidable.IncomingForm(),
files = [],
fields = {};
if(req.type === 'GET' || req.data.iframe){
resp.writeHead(200, {'content-type': mime.get("html")});
resp.end(uploadBase);
}
try{
form.uploadDir = req.data.uploadUrl ? ( root + "/" + req.data.uploadUrl + "/" ) : path.join( __dirname, "/../../static/" ); //上传路径
uploadModel = req.data.target ? (root + "/" + req.data.target) : (modelPath || uploadModel);
form.on('field', function(field, value) {
fields[field] = value;
})
.on('file', function(field, file) {
if( file.size ){
files.push({name: field, file: file});
}
})
.on('end', function() {
files.map(function(file){
fs.rename(file.file.path, form.uploadDir + file.file.name, function (err) {
if(err){ throw err; }
});
});
req.post = fields;
req.files = files;
var extType = path.extname(uploadModel).substring(1);
fs.readFile(uploadModel, function(err, data){
if(err){
throw err;
}
resp.writeHead(200, {'content-type': mime.get(extType)});
req.forward = true;
handle.execute.call(req,req,resp,root,data.toString(),mini.get(extType),true,conf);
});
});
form.parse(req);
}catch(e){
resp.writeHead(500, {"Content-Type": "text/html"});
resp.end( e.toString().replace(/\n/g,"<br>") );
}
};