在学习nodeJs的时候,照着文档做的,但是到最后的上传文件显示图片总是报错,
所用的fs.renameSync出错:Error: EXDEV, cross-device link not permitted,查了一下是因为上传的文件是传到C盘,要读取的文件在D盘;所以
fs.renameSync(files.upload.path, "/tmp/test.png");这一条就会报错;
解决方法是:
var readStream=fs.createReadStream(files.upload.path); console.log(files.upload.path) var writeStream=fs.createWriteStream("/tmp/test.jpg"); readStream.pipe( writeStream );
将文件先复制到同一个盘,在来读取。
最终的代码:
function upload(response,request){ var form = new formidable.IncomingForm(); form.parse(request, function(error, fields, files) { var readStream=fs.createReadStream(files.upload.path); var writeStream=fs.createWriteStream("/tmp/test.png"); readStream.pipe( writeStream ); response.writeHead(200, {"Content-Type": "text/html"}); response.write("received image:<br/>"); response.write("<img src='/show' />"); response.end(); }); }
var readStream=fs.createReadStream(files.upload.path); console.log(files.upload.path) var writeStream=fs.createWriteStream("/tmp/test.jpg"); /*util.pump(readStream,writeStream,function(){ fs.unlinkSync(files.upload.path); })*/ readStream.pipe( writeStream );