본문 바로가기
JavaScript

file upload (react.js + multer + axios)

by 들풀민들레 2024. 1. 24.
본 글은 교육시간에 교육생에게 도움을 주기 위해 작성되었습니다.

 

 

목적은 react.js - node.js 환경에서 파일 업로드 구현입니다.

front 에서 axios 를 이용하며 back-end 에서 multer 를 이용합니다. 

 

back-end 에 public 폴더를 static 폴더로 지정했다는 가정이고 이 public 하위에 upload 폴더에 파일을 저장합니다.

파일을 저장하자 마자 저장한 파일명을 front 에 전달해서 화면에 이미지로 출력하는 샘플입니다.

 

Front 코드

const App = () => {

  const [title, setTitle] = useState('')
  const [file, setFile] = useState()

  const [uploadImage, setUploadImage] = useState()
  

  const upload = async (e) => {
    e.preventDefault()
    console.log(title, file)
    if(file){
      const formData = new FormData();
      formData.append('file1',file)
      formData.append('title',title)
      const resp = await axios.post('http://localhost:8000/test2/upload', formData)
      if(resp.data.status === 200){
        alert('upload ok')
        setUploadImage(resp.data.data)
      }
    }else {
      alert('데이터를 입력하지 않았습니다.')
    }
  }

  return (
    <div>
      <form id="form" action="#" method="post" encType="multipart/form-data">
        <input type='text' name='title' value={title} onChange={(e) => setTitle(e.target.value)}/>
        <input type="file" name="file1" onChange={(e) => setFile(e.target.files[0])}/>
        <input type="button" value="업로드" onClick={upload}/>
      </form>
      <br/>
      { uploadImage ? <img src={`http://localhost:8000/upload/${uploadImage}`} /> : ''}
    </div>
  )
}

 

Back-End 코드

 

const upload = multer({
  storage: multer.diskStorage({
    destination(req, file, done) {
      done(null, 'public/upload/')
    },
    filename(req, file, done) {

      const ext = path.extname(file.originalname)
      done(null, path.basename(file.originalname, ext) + Date.now() + ext)
    }
  }),
  limits: { fileSize: 5 * 1024 * 1024 }
})

router.post('/upload', (req, res, next) => {
  const a1 = upload.single('file1');

  a1(req, res, function (err) {
    if (err instanceof multer.MulterError) {
      console.log(err)
      res.json({ status: 500, message: 'error' })
    } else if (err) {
      console.log(err)
      res.json({ status: 500, message: 'error' })
    } else {
      console.log('upload router....')
      const data = req.body
      console.log('title', data.title)
      console.log('file', req.file.filename)
      res.json({ status: 200, message: 'OK', data: req.file.filename })
    }
  })

})

'JavaScript' 카테고리의 다른 글

CORS 환경에서 Session 이용하기  (0) 2024.01.17
This...  (0) 2019.02.13