• 카테고리

    질문 & 답변
  • 세부 분야

    풀스택

  • 해결 여부

    미해결

파일을 저장하는데 실패했다고 뜹니다.

22.08.30 17:15 작성 조회수 397

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 FileUpload

product.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

0830에러.png

답변 2

·

답변을 작성해보세요.

0

최주용님의 프로필

최주용

2022.11.03

저도 같은문제 발생중인데, 혹시 해결방법 공유해주실 수 있으신가요...?

0

choc님의 프로필

choc

2022.09.02

혹시 FileUpload 컴포넌트에서 axios post요청할 때 config에 있는 header -> headers로 수정해 보시겠어요?

4ckdnjssu님의 프로필

4ckdnjssu

질문자

2022.09.14

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