Node.js强大的重命名上传的文件

试图完成“Node初学者书”这本书,最后我需要的是实现修改一个请求处理程序,它显示一个图像,在用户上传后重命名,我使用node-formidable和fs模块。

var fs = require("fs"), formidable = require("formidable"); function upload (resp, req) { var form = new formidable.IncomingForm(); form.parse(req, function (error, fields, files) { /* This is the part that doesn't work on Windows */ fs.rename(files.upload.path, "/tmp/test.png", function (error) { if (error) { fs.unlink("/tmp/test.png"); fs.rename(files.upload.path, "/tmp/test.png"); } }); resp.writeHead(200, {"Content-Type":"text/html"}); resp.write("Received image:<br/>"); resp.write("<img src=/show />"); resp.end(); }); } function show (resp) { fs.readFile("./tmp/test.png", "binary", function (error, file) { if (error) { resp.writeHead(500, {"Content-type":"text/plain"}); resp.write(error + "\n"); resp.end(); } else { resp.writeHead(200, {"Content-type":"image/png"}); resp.write(file, "binary"); resp.end(); } }); } 

为了好的措施,这里是html文件:

 <!doctype html> <html lang="en"> <head> <meta http-equiv="Content-type" content="text/html" charset="UTF-8"/> <title>First steps</title> </head> <body> <form action="/upload" enctype ="multipart/form-data" method="post"> <input type="file" name="upload"> <input type="submit" value="Upload file"> </form> </body> </html> 

在控制台,它给了我一个错误,fs.unlink和fs.rename缺less一个callback,但它确实去显示请求处理程序,但不显示图像。 有没有更简单的方法来做事情? 谢谢

经过不less试验和错误,我发现是什么阻止了代码的工作,有两个条件:

  • 所有"/tmp/test.png"链接都需要replace为"./tmp/test.png"以使它们相对于当前的项目文件夹

  • 需要在当前项目名为/tmp的文件夹中,它不需要包含任何内容,但它需要在那里,如果不是,那么Windows不能创build它。 我可能需要添加一些代码行来检查是否存在之前上传和重命名文件到这个文件夹。

其实,有谁知道为什么在地址栏中仍然显示http://localhost:8888/upload ? 我认为这将表明http://localhost:8888/show ?? !!

我有同样的问题,在我的情况下,这是因为文件被上传到我的C:驱动器上的临时位置,但项目文件是在我的D:驱动器,跨驱动器复制创buildfs.rename问题()。 我硬连接目标到C:驱动器,然后它工作正常。