programing

node.js를 이용한 이미지 업로드, 표시 및 저장 방법 및 표현 방법

codeshow 2023. 9. 19. 21:32
반응형

node.js를 이용한 이미지 업로드, 표시 및 저장 방법 및 표현 방법

이미지를 업로드하고 표시해야 하며 로컬 호스트를 새로 고치면 손실되지 않도록 저장해야 합니다.이 작업은 파일 선택을 묻는 "업로드" 단추를 사용하여 수행해야 합니다.

서버측 코드는 node.js와 express를 사용하고 있습니다.

우선 파일 입력 요소가 포함된 HTML 양식을 만들어야 합니다.또한 양식의 entype 속성을 다중 부분/양식 데이터로 설정해야 합니다.

<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(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 현재 프레임워크와 함께 제공되는 바디 파서는 없습니다.다행히 사용 가능한 여러 부품/양식 데이터 구문 분석기 중 하나를 선택할 수 있습니다.여기, 멀터를 사용하겠습니다.

양식 게시물을 처리할 경로를 정의해야 합니다.

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" />

당신은 당신의 익스프레스 앱에서 다른 경로를 정의하고 사용할 수 있습니다.res.sendFile저장된 이미지를 제공하는 방법:

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

반응형