far*_*jad 183
首先,您应该创建一个包含文件输入元素的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>
Run Code Online (Sandbox Code Playgroud)
假设形式中定义的index.html存储在一个名为公共相对于您的脚本所在,你可以成为这样说:
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")));
Run Code Online (Sandbox Code Playgroud)
完成后,用户将能够通过该表单将文件上传到您的服务器.但是,重新组装您的应用程序上传的文件,你需要解析请求体(如多形式的数据).
在Express 3.x中,您可以使用express.bodyParser
中间件来处理多部分表单,但是从Express 4.x开始,没有与框架捆绑在一起的正文解析器.幸运的是,您可以从众多可用的multipart/form-data解析器中选择一个.在这里,我将使用multer:
您需要定义处理表单帖子的路由:
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!");
});
}
}
);
Run Code Online (Sandbox Code Playgroud)
在上面的示例中,发布到/ upload的.png文件将保存到相对于脚本所在位置的上载目录中.
为了显示上传的图像,假设您已经有一个包含img元素的HTML页面:
<img src="/image.png" />
Run Code Online (Sandbox Code Playgroud)
您可以在快递应用中定义另一条路线,并用于res.sendFile
提供存储的图像:
app.get("/image.png", (req, res) => {
res.sendFile(path.join(__dirname, "./uploads/image.png"));
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
142177 次 |
最近记录: |