书中的实例代码当上传图片时会报Error: ENOENT, 原因:图片默认会选择系统的缓存文件夹下,在windows下无权访问C盘,所以就报错了。。
解决方法:只需要指定图片存放位置,在这之前要在指定的文件下手工创建tmp文件夹;
具体改动如下(红色标注为改动内容):
upload.js
1 var form = new formidable.IncomingForm(); 2 form.uploadDir = "tmp"; 3 form.parse(req, function(err, fields, files) { 4 5 console.log(files.upload.path); 6 try{ 7 fs.renameSync(files.upload.path, "tmp/test.png"); 8 }catch(e){ 9 console.log(e); 10 } 11 12 res.writeHead(200, {'content-type': 'text/plain'}); 13 res.write('received upload: '); 14 res.end(sys.inspect({fields: fields, files: files})); 15 });
当然,文件开头不要忘记引入fs模块 fs = require('fs')
requesthandle.js
function show(response, postData) { console.log("Request handler 'show' was called."); fs.readFile("tmp/test.png", "binary", function(error, file) { if(error) { response.writeHead(500, {"Content-Type": "text/plain"}); response.write(error + " "); response.end(); } else { response.writeHead(200, {"Content-Type": "image/png"}); response.write(file, "binary"); response.end(); } }); }
本人也刚刚开始研究nodejs,昨晚看了下这本书,上传搞了好久,在网上也google好久,仍不得其解,写出来以备忘,与大家共享,希望共同进步!
git地址:https://github.com/finderL/myapp
有误之处还请不吝赐教!