Nice programing

node.js 및 express를 사용하여 이미지를 업로드, 표시 및 저장하는 방법

nicepro 2020. 10. 11. 11:20
반응형

node.js 및 express를 사용하여 이미지를 업로드, 표시 및 저장하는 방법


이미지를 업로드하고 표시하고 로컬 호스트를 새로 고칠 때 잃어 버리지 않도록 저장해야합니다. 이 작업은 파일 선택을 요청하는 "업로드"버튼을 사용하여 수행해야합니다.

node.js를 사용하고 있으며 서버 측 코드로 표현합니다.


먼저 파일 입력 요소를 포함하는 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>

양식이 스크립트가있는 위치와 관련된 public 이라는 디렉토리에 저장된 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")));

완료되면 사용자는 해당 양식을 통해 서버에 파일을 업로드 할 수 있습니다. 그러나 애플리케이션에서 업로드 된 파일을 다시 어셈블하려면 요청 본문 (멀티 파트 양식 데이터)을 구문 분석해야합니다.

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

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

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

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

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

참고URL : https://stackoverflow.com/questions/15772394/how-to-upload-display-and-save-images-using-node-js-and-express

반응형