在写一个文件上传的功能时候,调用fs.renameSync方法错误
出错 代码所在如下:
function upload(response,request){ console.log("upload 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.jpg"); response.writeHead(200, {"Content-Type": "text/html"}); response.write("received image:<br/>"); response.write("<img src='/show' />"); response.end(); }); }
大致分析后,预计是因为 跨磁盘分区移动 或操作文件会有权限问题。
下面提供两种解决办法:
方法一:
主要利用fs的createReadStream、createWriteSream和unlinkSync方法
具体代码如下:
function upload(response,request){ console.log("upload 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.jpg"); var readStream=fs.createReadStream(files.upload.path); var writeStream=fs.createWriteStream("./tmp/test.jpg"); readStream.pipe(writeStream); readStream.on('end',function(){ fs.unlinkSync(files.upload.path); }); response.writeHead(200, {"Content-Type": "text/html"}); response.write("received image:<br/>"); response.write("<img src='/show' />"); response.end(); }); }
PS:我用的node版本是0.10.69,如果使用的是0.6以下的版本,可以使用util.pump
相应代码只需将上面的代码中readStream.on处改成:(注意引入util模块)
util.pump(readStream,writeStream, function() { fs.unlinkSync('files.upload.path'); });
方法二:
这种就简洁很多了
添加一个 form.uploadDir='tmp' 即可(写一个临时路径)
function upload(response,request){ console.log("upload 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.jpg"); response.writeHead(, {"Content-Type": "text/html"}); response.write("received image:<br/>"); response.write("<img src='/show' />"); response.end(); }); }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。