定义了 req.files 和 req.files

时间:2021-01-26 07:31:09

标签: javascript node.js reactjs multer

当我尝试使用 multer 上传单个图像和一组图像时,我被卡住了。该过程正在与邮递员合作,但在我通过 React 发布时提供未定义的 req.file(s)。 下面是代码片段

前端 product.js

class Products extends Component {
    state = {
        name: '',
        quantity: '',
        price: '',
        description: '',
        offer: '',
        manufacturer: '',
        expiryDate: null,
        photos: [],
        msg:'',
        show:false,
        approved:'',
        reviews: '',
        category: ''
    }
    static propTypes = {
        loadProducts: PropTypes.func.isRequired,
        saveProduct: PropTypes.func.isRequired,
        error500: PropTypes.bool,
        error: PropTypes.object.isRequired,
        clearErrors: PropTypes.func.isRequired,
        clearSuccess: PropTypes.func.isRequired,
        returnSuccess: PropTypes.func.isRequired
    }
    componentDidMount() {
        
        
        this.props.loadProducts()
        this.props.clearErrors()
        
        
        
    }
    componentDidUpdate(prevProps) {
        const { error} = this.props
        
        if (error !== prevProps.error) {
            //check for PRODUCT error
            if (error.id === 'PRODUCT-ERROR') {
                this.setState({ msg: error.msg.message })
            } else {
                this.setState({ msg: null })

            }
        }
        
        
    }
    handleChange = (e) => {
        this.setState({ [e.target.name]: e.target.value })
    }
    handleEditorChange = (description, editor) => {
        this.setState({'description': description});
      }
    handlePhotos =(e)=>{
       
        this.setState({photos:e.target.files})
        
    }
    handleSubmit =(e) =>{
        e.preventDefault();
        const { name,quantity,price,description, offer,manufacturer,
        expiryDate,photos,approved,reviews,category
        }= this.state
        
        const product ={name,quantity,price,description, offer,manufacturer,
            expiryDate,photos,approved,reviews,category};
        
        
        this.props.saveProduct(product);
        this.props.clearErrors()
    }
 <Form onSubmit={this.handleSubmit} enctype="multipart/form-data">
<Form.File
                                                        onChange={this.handlePhotos}
                                                        accept="image/*"
                                                        multiple
                                                        name='photos'
                                                        type='file'
                                                        placeholder="Product photos" />

前端 productAction.js

export const saveProduct =({ name,quantity,price,description, offer,manufacturer,
    expiryDate,photos,approved,reviews,category
    }) =>async (dispatch) =>{
        console.log(photos)
    //Headers
    const headers = {
        
            'Content-Type':'multipart/form-data'
            
        
    }
    //Request Body
    
    
    const data = { name,quantity,price,description, offer,manufacturer,
        expiryDate,photos,approved,reviews,category
        }
    
    console.log(data)
    await axios.post('http://127.0.0.1:2000/api/product/create',data,headers)
        
        .then(res =>{
            dispatch({
            type: CREATE_PRODUCT,
            payload: res.data,
            
            })
            dispatch(
                returnSuccess(res.data,res.status,'PRODUCT-CREAT-SUCCESS')
            )
            })

***后端product.js ***

//initialize app
const app= express();

//initialize cors
app.use(cors());

//initialize bodyparser
app.use(express.urlencoded({extended:true}));
app.use(express.json());
const storage = multer.diskStorage({
    
    filename:  function (req, file, cb) {
        cb(null, shortid.generate()+ '-' + file.originalname)
    },
})
const uploads = multer({storage:storage,fileFilter: (req, file, cb) => {
    if (file.mimetype == "image/png" || file.mimetype == "image/jpg" || file.mimetype == "image/jpeg") {
        cb(null, true);
    } else {
        cb(null, false);
        return cb(new Error('Only .png, .jpg and .jpeg format allowed!'));
    }
}});
router.post('/product/create',uploads.array('photos',10),
        async(req,res,next)=>{
            //res.status('200').json({file:req.files, body: req.body})
            let photos =[]
            console.log(req.files)

有人帮忙请被困几天

1 个答案:

答案 0 :(得分:0)

我遵循@Quentin 指南,在使用 FormData 和使用 e.target.files[0] 后,我设法发送了一个文件。 我必须添加 for (let i = 0; i < photos.length; i++) { data.append('photos', photos[i]) } 当我要附加多张照片时。在 handlePhotos 函数中 e.target.files

谢谢