Skip to content

Instantly share code, notes, and snippets.

@think2011
Last active Aug 29, 2015
Embed
What would you like to do?
node.js 上传图片实例
var formidable = require('formidable'),
http = require('http'),
util = require('util'),
fs = require('fs');
http.createServer(function(req, res) {
// 移除跨域限制
res.setHeader('Access-Control-Allow-Origin', '*');
if (req.url == '/upload' && req.method.toLowerCase() == 'post') {
// parse a file upload
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
res.writeHead(200, {
'content-type': 'text/plain'
});
res.write('received upload:\n\n');
// 存储图片到根目录下
fs.rename(files.upload.path, './' + files.upload.name, function () {
console.log('saved done');
});
res.end(util.inspect({
fields: fields,
files: files
}));
});
return;
}
// show a file upload form
res.writeHead(200, {
'content-type': 'text/html'
});
res.end(
'<form action="/upload" enctype="multipart/form-data" method="post">' +
'<input type="text" name="title"><br>' +
'<input type="file" name="upload" multiple="multiple"><br>' +
'<input type="submit" value="Upload">' +
'</form>'
);
}).listen(1991);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment