inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

따라하며 배우는 노드, 리액트 시리즈 - 쇼핑몰 사이트 만들기[전체 리뉴얼]

파일 업로드 실패 alert창

353

판다코딩

작성한 질문수 3

0

안녕하세요!

uploads 폴더 안에 파일은 잘 들어가는 것을 확인했으나,

사진을 등록하고자 하면 업로드 실패가 나옵니다.

무엇이 잘못되었을까요?

FileUploads.js

import React, { useState } from 'react'
import Dropzone from 'react-dropzone'
import { UploadOutlined } from '@ant-design/icons';
import axios from 'axios';
//import e, { response } from 'express';

function FileUpload() {

    const [Images, setImages] = useState([])

    const dropHandler = (files) => {

        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){
                    console.log(response.data)
                    setImages([...Images, response.data.filePath])
                }
                else{
                    console.log(response.data)
                    alert("파일 업로드 실패")
                }
                */
               setImages([...Images, response.data.filePath]
            })
    }
    return (
        <div style={{display:'flex', justifyContent: 'space-between'}}>
            <Dropzone onDrop={dropHandler}>
                {({getRootProps, getInputProps}) => (
                <div 
                    style={{width:300, height:240, border:'1px solid lightgray',
                            display:'flex', alignItems:'center', justifyContent:'center'
                        }}
                    {...getRootProps()}>
                    <input {...getInputProps()} />
                    <UploadOutlined style={{fontSize:'3rem'}}/>
                </div>
                )}
            </Dropzone>

            <div  style={{width:350, height:240, overflowX:'scroll'}}>

                    {Images.map((image, index) => {
                        <div key={index}>
                            <img style={{ minWidth:'300px', width:'300px', height:'240px'}}
                            src={`http://locallhost:5000/${image.filePath}`} />
                        </div>
                    })}
            </div>
        </div>
    )
}

export default FileUpload

product.js

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

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

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        //파일 저장 위치
        cb(null, 'uploads/')
    },
    filename: function (req, file, cb) {
      cb(null, `${Date.now()}_${file.originalname}`)
    }
  })
   
  var upload = multer({ storage: storage }).single("file")

  
router.post('/image', (req, res) => {
    //image save
    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})
    })
})

module.exports = router;

  만약 FileUpload.js 에서 if-else문 없이

setImages([...Imagesresponse.data.filePath])

로 바로 정의하면 

×

TypeError: Cannot read property 'filePath' of undefined

와 같은 에러가 나옵니다.

웹앱 react mongodb nodejs redux

답변 1

0

판다코딩

앗 해결되었습니다~~

강의 내용은 훌륭하나, 환경 설정 오류 때문에 진도를 나갈 수 없습니다. 20년 버전 강의.

0

60

1

강의자료는 어디서 볼 수있나요??

0

66

1

이 쇼핑몰 만들기 강의는 관리자페이지 만드는건 없나요

0

113

2

웹에서 실시간 코드반영이 안돼요

0

120

1

app.use질문

0

64

1

강사님께 어떻게 직접질문할수있어요??

0

75

1

const함수같은거 기초강의는 어디있나요

0

81

2

리덕스 참조챕터가 어딨어요? 미리듣고오라는데요

0

81

2

강의가완전 오래되서 다 틀리네 app.jsx도 tailwind css 다틀림 무책임함

0

68

1

개발자도구에 redux란이 없어요

0

88

1

npx tailwindcss init -p 에서 계속 에러나요

0

92

1

쇼핑몰기능중 찜하기 기능은 어떻게 구현하나요

0

138

2

강의하다 줌으로 설명가능한지좀 정확히 알려주세요. 이 선생님 정책이 어떻게 되는데요. 직접 연락할 메일이라도 알려주세요

0

43

1

도표 강의 자료 열람 불가능

0

109

1

tailwindcss를 vite에서 이용하는 방식이 바뀐것 같습니다.

0

1132

2

eslint 설정 후 오류가 납니다.

0

222

1

오버로드 오류

0

150

1

VSCode에서 save를 할 때, landingpage의 useEffect가 실행되는 문제에 대하여

0

169

1

dispatch(logoutUser()) 실행시 dispatch(authuser())도 함께 실행되는 문제

0

228

2

logout할 때, server로 요청을 보내서 authUser middleware를 통과하도록 하는 이유?

0

195

1

webkit-text-size-adjust 오류

0

314

1

does not provide an export named 'userReducer'

0

217

2

빌드 배포

0

140

1

삭제 예정 강의는 언제 삭제 되나요? 저것때문에 수강완료를 못하면 회사에서 비용을 청구한다고 합니다~

0

220

2