本文转载自:http://www.cnblogs.com/glczero/p/3932024.html
Node.js,在写一个文件上传的功能时候,调用fs.renameSync方法错误
function upload(response,request){ console.log("requestHander upload was called") var form = new formidable.IncomingForm(); console.log("about to parse"); form.parse(request,function(error,fields,files){ console.log("parsing done"); fs.renameSync(files.upload.path,"./tmp/test.png"); response.writeHead(200,{"Content-Type":"text/html"}); response.write("reveived image : <br/>"); response.write("<img src='/show' />"); response.end(); }) /*response.writeHead(200,{"Content-Type":"text/plain"}); response.write("you have sent:"+querystring.parse(request).text); response.end();*/ }
大致分析后,预计是因为跨磁盘分区移动或操作文件会有权限问题。
下面提供两种解决办法:
方法一:
主要利用fs的createReadStream、createWriteSream和unlinkSync方法
具体代码如下:
function upload(response,request){ console.log("requestHander upload was called") var form = new formidable.IncomingForm(); //form.uploadDir='tmp'; console.log("about to parse"); form.parse(request,function(error,fields,files){ console.log("parsing done"); //fs.renameSync(files.upload.path,"./tmp/test.png"); var readStream=fs.createReadStream(files.upload.path); var writeStream=fs.createWriteStream("./tmp/test.png"); readStream.pipe(writeStream); readStream.on('end',function(){ fs.unlinkSync(files.upload.path); }) response.writeHead(200,{"Content-Type":"text/html"}); response.write("reveived image : <br/>"); response.write("<img src='/show' />"); response.end(); }) /*response.writeHead(200,{"Content-Type":"text/plain"}); response.write("you have sent:"+querystring.parse(request).text); response.end();*/ }
方法二:
这种就简洁很多了
添加一个 form.uploadDir='tmp' 即可(写一个临时路径)
function upload(response,request){ console.log("requestHander upload was called") var form = new formidable.IncomingForm(); form.uploadDir='tmp'; console.log("about to parse"); form.parse(request,function(error,fields,files){ console.log("parsing done"); fs.renameSync(files.upload.path,"./tmp/test.png"); response.writeHead(200,{"Content-Type":"text/html"}); response.write("reveived image : <br/>"); response.write("<img src='/show' />"); response.end(); }) /*response.writeHead(200,{"Content-Type":"text/plain"}); response.write("you have sent:"+querystring.parse(request).text); response.end();*/ }