• 카테고리

    질문 & 답변
  • 세부 분야

    풀스택

  • 해결 여부

    미해결

파일 업로드 실패 alert창

20.11.05 05:09 작성 조회수 179

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

와 같은 에러가 나옵니다.

답변 1

답변을 작성해보세요.

0

앗 해결되었습니다~~