如何使用 node.js 和 express 上传、显示和保存图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15772394/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to upload, display and save images using node.js and express
提问by user1602123
I need to upload an image, and display it, as well as save it so that I don't lose it when I refresh the localhost. This needs to be done using an "Upload" button, which prompts for a file-selection.
我需要上传一个图像,并显示它,并保存它,这样我在刷新本地主机时就不会丢失它。这需要使用“上传”按钮来完成,该按钮会提示选择文件。
I am using node.js and express for the server-side code.
我正在使用 node.js 并表达服务器端代码。
回答by fardjad
First of all, you should make an HTML form containing a file input element. You also need to set the form's enctypeattribute to multipart/form-data:
首先,您应该制作一个包含文件 input 元素的 HTML 表单。您还需要将表单的enctype属性设置为multipart/form-data:
<form method="post" enctype="multipart/form-data" action="/upload">
<input type="file" name="file">
<input type="submit" value="Submit">
</form>
Assuming the form is defined in index.htmlstored in a directory named publicrelative to where your script is located, you can serve it this way:
假设表单是在index.html中定义的,存储在一个名为public的目录中,相对于您的脚本所在的位置,您可以通过以下方式提供它:
const http = require("http");
const path = require("path");
const fs = require("fs");
const express = require("express");
const app = express();
const httpServer = http.createServer(app);
const PORT = process.env.PORT || 3000;
httpServer.listen(3000, () => {
console.log(`Server is listening on port ${PORT}`);
});
// put the HTML file containing your form in a directory named "public" (relative to where this script is located)
app.get("/", express.static(path.join(__dirname, "./public")));
Once that's done, users will be able to upload files to your server via that form. But to reassemble the uploaded file in your application, you'll need to parse the request body (as multipart form data).
完成后,用户将能够通过该表单将文件上传到您的服务器。但是要在您的应用程序中重新组装上传的文件,您需要解析请求正文(作为多部分表单数据)。
In Express 3.xyou could use express.bodyParsermiddleware to handle multipart forms but as of Express 4.x, there's no body parser bundled with the framework. Luckily, you can choose from one of the many available multipart/form-dataparsers out there. Here, I'll be using multer:
在Express 3.x 中,您可以使用express.bodyParser中间件来处理多部分表单,但从Express 4.x 开始,没有与框架捆绑的正文解析器。幸运的是,您可以从众多可用的multipart/form-data解析器中进行选择。在这里,我将使用multer:
You need to define a route to handle form posts:
您需要定义一个路由来处理表单帖子:
const multer = require("multer");
const handleError = (err, res) => {
res
.status(500)
.contentType("text/plain")
.end("Oops! Something went wrong!");
};
const upload = multer({
dest: "/path/to/temporary/directory/to/store/uploaded/files"
// you might also want to set some limits: https://github.com/expressjs/multer#limits
});
app.post(
"/upload",
upload.single("file" /* name attribute of <file> element in your form */),
(req, res) => {
const tempPath = req.file.path;
const targetPath = path.join(__dirname, "./uploads/image.png");
if (path.extname(req.file.originalname).toLowerCase() === ".png") {
fs.rename(tempPath, targetPath, err => {
if (err) return handleError(err, res);
res
.status(200)
.contentType("text/plain")
.end("File uploaded!");
});
} else {
fs.unlink(tempPath, err => {
if (err) return handleError(err, res);
res
.status(403)
.contentType("text/plain")
.end("Only .png files are allowed!");
});
}
}
);
In the example above, .pngfiles posted to /uploadwill be saved to uploadeddirectory relative to where the script is located.
在上面的示例中,发布到/upload 的.png文件将保存到与脚本所在位置相关的上传目录中。
In order to show the uploaded image, assuming you already have an HTML page containing an imgelement:
为了显示上传的图像,假设您已经有一个包含img元素的 HTML 页面:
<img src="/image.png" />
you can define another route in your express app and use res.sendFileto serve the stored image:
您可以在 Express 应用程序中定义另一条路线并用于res.sendFile提供存储的图像:
app.get("/image.png", (req, res) => {
res.sendFile(path.join(__dirname, "./uploads/image.png"));
});

