Last active
August 29, 2015 14:13
-
-
Save think2011/4c60f2755a58abbad840 to your computer and use it in GitHub Desktop.
node.js 上传图片实例
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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