Just Do IT!

react-dropzone 라이브러리 사용하기 (+ multer 라이브러리) 본문

개발 공부

react-dropzone 라이브러리 사용하기 (+ multer 라이브러리)

MOON달 2024. 1. 17. 17:34
728x90
react-dropzone 라이브러리란?

파일 업로드 라이브러리이다.

간단하게 drag&drop으로도 사용 가능하고 클릭하여 파일을 업로드할 수도 있다.

그리고 이미지 썸네일 미리보기를 지원하며 멀티 업로드 기능 역시 지원한다.

 

https://www.npmjs.com/package/react-dropzone

 

https://www.npmjs.com/package/react-dropzone

react-dropzone Simple React hook to create a HTML5-compliant drag'n'drop zone for files. Documentation and examples at https://react-dropzone.js.org. Source code at https://github.com/react-dropzone/react-dropzone/. Installation Install it from npm and inc

www.npmjs.com

 

 

 

 

 

 

 

 

간단한 설치 방법

 

npm install react-dropzone --save

 

 

+) yarn을 사용할 수도 있다.

 

 

 

 

 

적용 예시

 

<Dropzone onDrop={onDrop} multiple={false} maxSize>
            {({ getRootProps, getInputProps }) => (
              <div
                style={{
                  width: "300px",
                  height: "240px",
                  border: "1px solid lightgray",
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                }}
                {...getRootProps()}
              >
                <input {...getInputProps()} />
                <Icon type="plus" style={{ fontSize: "3rem" }} />
              </div>
            )}
          </Dropzone>

 

간단하게 style을 지정할 수도 있다.

이 프로젝트에서는 antd 라이브러리를 사용했기 때문에 Icon을 넣어주었다.

 

onDrop 함수를 통해 업로드 할 수 있다.

 

 

 

이런 식으로 antd를 사용해 간단하게 만들어 볼 수 있다.

저 + 아이콘을 클릭하면 바로 컴퓨터에 저장된 파일을 저장할 수 있다.

 

+ 클릭했을 때 업로드 가능하게 나온다

 

 

 

 

 

 

여기서,

프론트와 백엔드의 연결이 이루어져야 한다.

파일을 올리면 백엔드 서버에 저장하고, 저장한 파일의 정보를 프론트로 가져와야하기 때문이다.

 

파일을 저장할 때,

multer 라이브러리를 사용할 수 있다.

 

 

 

 

 

 

 

multer 라이브러리란?

 

파일 업로드를 위해 사용되는 multipart/form-data를 다루기 위한 node.js의 미들웨어이다.

middleWare로 기능하기 때문에 API의 요청에 대한 응답이 오기 전에 이미 한번 거쳐가는 방식이라 API요청에 대한 응답의 올바름 또는 에러와 상관 없이 관련 저장소에 저장하게 된다.


https://www.npmjs.com/package/multer

 

multer

Middleware for handling `multipart/form-data`.. Latest version: 1.4.5-lts.1, last published: 2 years ago. Start using multer in your project by running `npm i multer`. There are 4086 other projects in the npm registry using multer.

www.npmjs.com

 

 

 

설치하기

 

npm install muler --save

 

 

 

 

 

적용 예시

 

const express = require("express");
const router = express.Router();
const { Video } = require("../models/Video");

const multer = require("multer");
var ffmpeg = require("fluent-ffmpeg");

var storage = multer.diskStorage({
  // 어디에 파일을 저장할지 설명 (upload 폴더에 저장)
  destination: (req, file, cb) => {
    cb(null, "uploads/");
  },
  // 어떤 파일 이름으로 저장할 것인지
  filename: (req, file, cb) => {
    cb(null, `${Date.now()}_${file.originalname}`);
  },
  // 동영상만 받을 거기 때문에 .mp4로 제한
  fileFilter: (req, file, cb) => {
    const ext = path.extname(file.originalname);
    if (ext !== ".mp4") {
      return cb(res.status(400).end("only jpg, png, mp4 is allowed"), false);
    }
    cb(null, true);
  },
});

var upload = multer({ storage: storage }).single("file");

router.post("/uploadfiles", (req, res) => {
  // 비디오를 서버에 저장한다
  upload(req, res, (err) => {
    if (err) {
      return res.json({ success: false, err });
    }
    return res.json({
      success: true,
      filePath: res.req.file.path,
      fileName: res.req.file.filename,
    });
  });
});

 

위의 코드처럼, multer 라이브러리를 사용하여 서버에 저장할 수 있다.

 

storage에서 파일을 저장 할 경로와 이름을 설정 할 수 있는데, file인수에서 다음 속성으로 파일 정보를 얻을 수 있다.

  • fieldname : html 폼에 정의된 필드 명
  • originalname : 사용자가 업로드 한 파일 명
  • size : 파일 사이즈 (byte 단위)
  • mimetype : 파일 타입

 

limits

파일 관련한 크기를 제어하는 속성이다. 단순히 파일 용량 뿐만 아니라 필드 이름에 대한 사이즈도 제어할 수 있다. 최대한 엄격하게 관리해야 혹시나 받을 수 있는 외부 공격에 대해 도움이 될 수 있다.

  • fieldNameSize : 필드 이름 최대 값 (기본 : 100 Byte)
  • fileSize : 파일 크기 최대 값 (기본 : 무제한)
  • files : 파일 필드의 최대 갯수 (기본 : 무제한)

 

filmfilter

파일의 유형을 필터링할 수 있다. 위의 예시에서는 mp4만 가능하도록 필터링했다.

 

single

파일 하나만 업로드하도록 제한을 둔 것이다. 여러 파일 업로드도 가능하다.

'개발 공부' 카테고리의 다른 글

[Python] 기본 문법 정리  (2) 2023.11.26