试图完成这本书“节点初学者书”,我需要做的最后一件事是修改一个请求处理程序,它显示一个图像,在用户上传后重命名,我正在使用 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 缺少回调,但是它确实转到了显示请求处理程序但不显示图像。有没有更简单的方法来做事?谢谢