如何使用 node.js 和 express 上传、显示和保存图像 [英] How to upload, display and save images using node.js and express

查看:39
本文介绍了如何使用 node.js 和 express 上传、显示和保存图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

I am using node.js and express for the server-side code.

推荐答案

首先,你应该制作一个包含 文件输入元素.您还需要设置表单的enctype 属性到 multipart/form-data:

First of all, you should make an HTML form containing a file input element. You also need to 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 的目录中,相对于您的脚本所在的位置,您可以这样提供:

Assuming the form is defined in index.html stored in a directory named public relative to where your script is located, you can serve it this way:

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")));

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

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).

Express 3.x 中,您可以使用 express.bodyParser 中间件来处理多部分表单,但在 Express 4.x 中,没有与框架捆绑在一起的正文解析器.幸运的是,您可以从 许多可用的multipart/form-data 解析器.在这里,我将使用 multer:

In Express 3.x you could use express.bodyParser middleware 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-data parsers out there. Here, I'll be using 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!");
      });
    }
  }
);

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

In the example above, .png files posted to /upload will be saved to uploaded directory relative to where the script is located.

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

In order to show the uploaded image, assuming you already have an HTML page containing an img element:

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

你可以在你的 express 应用中定义另一个路由并使用 res.sendFile 来提供存储的图像:

you can define another route in your express app and use res.sendFile to serve the stored image:

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

这篇关于如何使用 node.js 和 express 上传、显示和保存图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆