node入门原书地址:https://www.nodebeginner.org/index-zh-cn.html
node入门,循序渐进讲了javascript,node的回调和一些api的应用,很清晰,翻译也很给力。最终是一个例子,可以上传图片以及展示。
最后例子,遇到了麻烦,运行报错
可见零时文件已经创建
代码如下
1 function upload(response, request){ 2 console.log("Request handler ‘upload‘ was called."); 3 4 var form = new formidable.IncomingForm(); 7 form.parse(request,function(error, fields, files){ 8 console.log("parsing done"); 9 console.log("F.U.P: "+files.upload.path); 10 fs.renameSync(files.upload.path, "tmp/test.png"); 11 response.writeHead(200, {"Content-Type": "text/html"}); 12 response.write("received image:<br/>"); 13 response.write("<img src=‘/show‘ />"); 14 response.end(); 15 }); 16 17 };
搜过以后发现是fs.renameSync()不能跨盘操作,且不会新建文件夹,所以重新指定路径“form.uploadDir = "tmp"”,然后在目录新建tmp文件夹,最后在show函数读取的路径做修改
修改后代码
1 function upload(response, request){ 2 console.log("Request handler ‘upload‘ was called."); 3 4 var form = new formidable.IncomingForm(); 5 form.uploadDir = "tmp"; 6 //console.log("about to parse"); 7 form.parse(request,function(error, fields, files){ 8 console.log("parsing done"); 9 console.log("F.U.P: "+files.upload.path); 10 /** 11 try{ 12 fs.renameSync(files.upload.path, "tmp/test.png"); 13 }catch(e){ 14 console.log(e); 15 }; 16 17 fs.renameSync(files.upload.path, "tmp/test.png",function(error){ 18 if(error){ 19 fs.unlink("/tmp/test.png"); 20 fs.rename(files.upload.path,"/tmp/test.png"); 21 }; 22 }); 23 **/ 24 fs.renameSync(files.upload.path, "tmp/test.png"); 25 response.writeHead(200, {"Content-Type": "text/html"}); 26 response.write("received image:<br/>"); 27 response.write("<img src=‘/show‘ />"); 28 response.end(); 29 }); 30 31 }; 32 33 function show(response){ 34 console.log("Request handle ‘show‘ was called."); 35 fs.readFile("./tmp/test.png","binary",function(error,file){ 36 if(error){ 37 response.writeHead(500,{"Content-Type":"text/plain"}); 38 response.write(error + "\n"); 39 response.end(); 40 }else{ 41 response.writeHead(200,{"Content-Type":"image/png"}); 42 response.write(file,"binary"); 43 response.end(); 44 }; 45 }); 46 };
第五行及第35行有修改
时间: 2024-10-22 11:02:05