【问题标题】:How to upload, display and save images using node.js and express [closed]如何使用 node.js 和 express 上传、显示和保存图像 [关闭]
【发布时间】:2013-03-24 05:40:17
【问题描述】:

我需要上传一张图片,并显示它,并保存它,这样我在刷新本地主机时就不会丢失它。这需要使用“上传”按钮来完成,该按钮会提示选择文件。

我正在使用 node.js 并表示服务器端代码。

【问题讨论】:

  • 103 用户不认为这个问题模棱两可、含糊不清、不完整、过于宽泛或夸夸其谈。有趣的。 ;)
  • 您还可以使用multer进行文件或图像上传,使用sharp js进行图像处理以及对图像进行调整大小或压缩等操作

标签: image node.js upload express


【解决方案1】:

首先,您应该制作一个包含file input element 的HTML 表单。你还需要set the form's enctype attribute to multipart/form-data:

<form method="post" enctype="multipart/form-data" action="/upload">
    <input type="file" name="file">
    <input type="submit" value="Submit">
</form>

假设表单在 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(PORT, () => {
  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")));

完成后,用户将能够通过该表单将文件上传到您的服务器。但是要在您的应用程序中重新组装上传的文件,您需要解析请求正文(作为多部分表单数据)。

Express 3.x 中,您可以使用 express.bodyParser 中间件来处理多部分表单,但从 Express 4.x 开始,框架中没有绑定正文解析器。幸运的是,您可以选择many available multipart/form-data parsers out there 之一。在这里,我将使用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!");
      });
    }
  }
);

在上面的示例中,发布到 /upload.png 文件将保存到相对于脚本所在位置的 uploaded 目录中。

为了显示上传的图片,假设您已经有一个包含 img 元素的 HTML 页面:

<img src="/image.png" />

您可以在您的快递应用中定义另一条路线,并使用res.sendFile 提供存储的图像:

app.get("/image.png", (req, res) => {
  res.sendFile(path.join(__dirname, "./uploads/image.png"));
});

【讨论】:

  • 你先生是个绅士和学者
  • 对于任何想要访问“req.files”或“req.body”的人,body-parser 现在只处理 JSON,请查看 github.com/expressjs/multer
  • as "app.use(express.bodyParser({uploadDir:'...'}));"不再工作的人应该使用“app.use(bodyParser({uploadDir:'...'}));”。因此 body-parser 必须通过 npm 添加并通过“var bodyParser = require('body-parser');”添加到您使用它的文件中
  • 我们如何在 express 4 中做到这一点?
  • @fardjad 如果我之间有角度怎么办?
猜你喜欢
  • 1970-01-01
  • 2018-03-19
  • 2016-12-24
  • 1970-01-01
  • 2020-03-22
  • 1970-01-01
  • 1970-01-01
  • 2011-07-06
  • 1970-01-01
相关资源
最近更新 更多