140

ローカルホストを更新したときに失われないように、画像をアップロードして表示し、保存する必要があります。これは、ファイルの選択を促す「アップロード」ボタンを使用して行う必要があります。

私は node.js を使用しており、サーバー側のコードには Express を使用しています。

4

1 に答える 1

309

まず、file 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>

フォームが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の時点では、フレームワークにバンドルされているボディ パーサーはありません。幸いなことに、利用可能な多数のmultipart/form-dataパーサーから 1 つを選択できます。ここでは、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ファイルは、スクリプトが配置されている場所に関連するアップロードされたディレクトリに保存されます。

アップロードされた画像を表示するには、すでにimg要素を含む HTML ページがあると仮定します。

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

Express アプリで別のルートを定義しres.sendFile、保存された画像を提供するために使用できます。

app.get("/image.png", (req, res) => {
  res.sendFile(path.join(__dirname, "./uploads/image.png"));
});
于 2013-04-02T20:00:07.317 に答える