gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 23:09:05 25 4
gpt4 key购买 nike

试图完成“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 缺少回调,但它确实转到显示请求处理程序,但不显示图像。有没有更简单的方法来做事?谢谢

最佳答案

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

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

  • 当前项目中需要有一个名为 /tmp 的文件夹,它不需要包含任何内容,但它必须存在,否则 Windows 无法创建它。在将文件上传并重命名到此文件夹之前,我可能需要添加一些代码行来检查它是否存在。

实际上,有谁知道为什么地址栏中仍然显示 http://localhost:8888/upload ?我认为它会指示 http://localhost:8888/show ??!!

关于Node.js 强大的重命名上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22877508/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com