본문 바로가기

react-shop-web/front & back

multer를 이용하여 이미지 저장

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

 

multer

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

www.npmjs.com

 

muter npm 페이지에 나와있는 다음 코드를 product.js 파일에 갖고오자. 

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, '/tmp/my-uploads')
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
    cb(null, file.fieldname + '-' + uniqueSuffix)
  }
})

const upload = multer({ storage: storage })

 

위 코드를 보면 destination이 있는데 이 부분은 어디에 파일이 저장이 되는지를 지정하는 것이고,

filename 부분은 uploads 폴더에 파일을 저장할 때 어떠한 이름으로 저장할 지 지정해주는 것이다.

 

이 프로젝트에선 root 부분에서 uploads라는 폴더에다가 모든 이미지를 넣어줄거다. 

그러므로 root경로에서 uploads라는 폴더를 만들어주자.

 

그리고 upload를 호출하여 client로 파일 저장 정보를 전달해주자.

const express = require('express');
const router = express.Router();
const multer = require('multer')

//=================================
//             Product
//=================================

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        // 밑에처럼 설정해주면 모든 파일이 uploads 폴더에 저장된다.
    cb(null, 'uploads/')
  },
  filename: function (req, file, cb) {
    cb(null, `${Date.now()}_${file.originalname}`) 
  }
})

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

router.post('/image', (req, res) => {

    // 가져온 이미지를 저장 해주는 부분 
    upload(req, res, err => {
        if(err){
            return res.json({success: false, err})
        }
        // 백엔드에서 파일 저장과 파일 저장 정보를 전달해주는데
        // 파일을 어디다가 저장했는지, 파일 이름은 무엇으로 정했는지 이 두가지를 client에 전달한다. 
        return res.json({success:true, filePath:res.req.file.path, fileName:res.req.filename})
    })
})

module.exports = router;

product.js

 

다음으로 FileUpload.js 파일에서 console.log로 백엔드로 부터 받은 정보를 출력해보면 

위 이미지처럼 정보를 잘 받은 것을 확인할 수 있다.

 

client에서 확인 버튼을 누르면 해당 이미지를 백엔드에 같이 전달해줘야 되기 때문에 이 이미지 정보를 state에 저장을 해줘야한다.

 

state에 이미지 경로들을 모두 저장했다면 

이미지 파일을 dropzone에 올렸을 때 옆에 이미지가 뜰 수 있도록 UI를 만들어주자.

 

import React, { useState } from 'react'
import Dropzone from 'react-dropzone'
import {Icon} from 'antd'
import axios from 'axios'

function FileUpload() {

    // 백엔드로부터 받은 이미지 경로를 저장한다. 
    // 이때 state는 배열로 구현하는데 이유는 이미지를 올릴 때 한 장만 올리는게 아니라 여러 장 올릴 수 있도록 구현하기 때문
    const [Images, setImages] = useState([])

    const dropHandler = (files) => {

        let formData = new FormData();

        const config = {
            header: {'content-type': 'multierpart/form-data'}
        }
        formData.append("file", files[0])

      axios.post('/api/product/image', formData, config)
        .then(response => {
          if (response.data.success) {
            //spread operator를 이용해서 기존에 있던 이미지들 까지 모두 갖고와서 새로운 이미지와 같이 저장해준다. 
            setImages([...Images, response.data.filePath])
          } else {
            alert('파일을 저장하는데 실패하였습니다.')
          }
        })
    }

  return (
    <div style={{display:'flex', justifyContent: 'space-between'}}>
        <Dropzone onDrop={dropHandler}>
                {({getRootProps, getInputProps}) => (
                    <section>
                      <div style={{width:300, height:240, border:'1px solid lightgray', display:'flex', alignItems:'center', justifyContent:'center'}}
                          {...getRootProps()}>
                          <input {...getInputProps()} />
                          <Icon type="plus" style={{fontSize: '3rem'}} />
                    </div>
                    </section>
                )}
        </Dropzone>

      <div style={{display: 'flex', width:'350px', height:'240px', overflowX:'scroll'}}>
        {Images.map((image, index) => (
          <div key={index}>
            <img style={{ minWidth: '300px', width: '300px', height: '240px' }}
                src={`https://5000-tjdvyzl-reactshopweb-4wj2unwwm8v.ws-us83.gitpod.io/${image}`}
            />
            </div>
        ))}            
        </div>
    </div>
  )
}

export default FileUpload

FileUpload.js

 

나는 gitpod을 쓰고있으므로 경로에는 그때그때 새로 갱신되는 백엔드 서버 주소를 넣어줘야한다.