Skip to content

Instantly share code, notes, and snippets.

@think2011
Last active August 29, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save think2011/4c60f2755a58abbad840 to your computer and use it in GitHub Desktop.
Save think2011/4c60f2755a58abbad840 to your computer and use it in GitHub Desktop.
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