인프런 커뮤니티 질문&답변
파일을 저장하는데 실패했다고 뜹니다.
작성
·
605
0
서버쪽에 문제가 있는 것일까요?
uploads 폴더에 들어가보면 사진은 저장이 잘 되어 있습니다.
FileUpload.js
import React, {useState} from 'react'
import Dropzone from 'react-dropzone'
import { Icon } from 'antd';
import axios from 'axios';
function FileUpload() {
  const [Images, setImages] = useState([]);
  //이미지를 몇개 올릴 수 있게 하기 위해서 배열로 생성
  const dropHandler = (files) => {
    // 파일을 backend에 전달해줘야 한다.
    // 그리고 파일을 전달 할 때 따로 해줘야 하는게 있다.
    let formData = new FormData();
    const config = {
      header: { 'content-type': 'multipart/form-data'}
    };
    formData.append("file", files[0]);
    axios.post('/api/product/image', formData, config).then((response) => {
        if (response.data.success){
            setImages([...Images, response.data.filePath])
        } else {
            alert('파일을 저장하는데 실패했습니다.')
        }
      });
    // formData와 config를 넣어주지 않으면은 파일을 보낼 때 에러가 발생하게 된다. 
  };
  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={`http://localhost:5000/${image}`} 
                />
              </div>  
            ))}
          </div>
    </div>
  )
}
export default FileUploadproduct.js
const express = require('express');
const router = express.Router();
const multer = require('multer');
//=================================
//             Product
//=================================
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
      cb(null, 'uploads/')
    }, 
    filename: function (req, file, cb) {
      const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
      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 req.json({ success: false, err})
        }
        return res.json({ seuccess: true, filePath: res.req.file.path, fileName: res.req.file.filename })
        // 파일을 어디에, 무슨 이름으로 저장했는지 전달해주는 역할
    })
})
module.exports = router;
index.js







해결했습니다! product .js 파일에서 오타가 있었더라고요 ㅠㅠ 감사합니다