【问题标题】:TypeError: Cannot read property 'path' of undefined when using cloudinaryTypeError:使用 cloudinary 时无法读取未定义的属性“路径”
【发布时间】:2019-10-20 07:31:24
【问题描述】:

我正在尝试将文件从 react 上传到 express 服务器。但是我收到此错误

TypeError: 无法读取未定义的属性“路径”

我正在使用 react 将文件传递/上传到服务器。

我引用了一个类似的问题,但它并不特定于 react js 传递文件

How to fix 'TypeError: Cannot read property 'path' of undefined' in Nodejs(Multer)

react 显示选定的图像,因此 react 可以很好地获取图像。

routes/images.js

import express from 'express';
import passport from 'passport';
import multer from 'multer';
import Image from '../models/Image'
import cloudinary from 'cloudinary';
import multipart from 'connect-multiparty';
import var_dump from 'var_dump';
import dd from 'dump-die';

const multipartMiddleware = multipart();

const cloud = cloudinary.v2
const router = express.Router();

const storage = multer.memoryStorage();
const upload = multer({ storage, dest:'uploads/'}); 

const params = {
    width: 250, 
    height:250, 
}

cloudinary.config({
    cloud_name: process.env.cloudinaryName,
    api_key: process.env.cloudinaryKey,
    api_secret: process.env.cloudinarySecret,
})



router.post('/upload',  multipartMiddleware,  upload.single('image'),  (req, res) => {
    cloud.uploader.upload(req.file.path,  (err, result) => {
        // dd(req.files);
        if(err){
            return res.status(500).send(err);
        }
       console.log(result);
        debugger;
        // const img = new Image({
        //     img_url:result,
        //     image_title:null
        // });

        // console.log(img);

        // img.save().then( img => {
        //     return res.status(200).json(img);
        // });

    });
});

export default router;

反应

import React, { Component } from "react";
import Button from '@material-ui/core/Button';
import Grid from '@material-ui/core/Grid';
import Typography from '@material-ui/core/Typography';
import ImageUploader from 'react-images-upload';
import Axios from '../Axios';
import Image from './Image';
class Dashboard extends Component{
    constructor(){
        super()
        this.state = {
            image_url: 'http://www.conservewildlifenj.org/images/artmax_1001.jpg', 
            selectedFile: null
        }
    }
    // handleChange = file => {
    //     const img = file[0]
    //     this.setState({
    //         selectedFile: img
    //     })
    //     debugger;
    // }
    handleUpload = ( file) =>   {

        const data = new FormData()
        const image = file[0]
        const image_url = image.name
        console.log(image.name);
        console.log(this.state.selectedFile);
        data.append('file',this.state.selectedFile)
        data.append('name',image_url)
        // data.append('description', 'some value user types')
        Axios.post('/images/upload', data).then((response) => {
            console.log(response);
            debugger;
            this.setState({
                image_url: response.data.fileUrl
            })
        });
    }
    render(){
        return(
            <div>
            <Grid container justify="center" spacing={16}>
                <Grid item sm={8} md={6} style={{ margin: '40px 0px', padding: '0px 30px'}}>
                    <Typography align="center" variant="h6">
                        Welcome to the Dashboard
                    </Typography>
                    <ImageUploader
                        withIcon={true}
                        withPreview={true}
                        buttonText='Upload an image'
                        imgExtension={['.jpg', '.gif', '.png', '.gif']}
                        onChange={this.handleUpload}
                        maxFileSize={5242880}
                    />
                     <Image image_url={this.state.image_url}/>
                </Grid>
                {/* Images  */}
              </Grid>
            </div>
        )
    }
}
export default Dashboard;

【问题讨论】:

  • 你为什么同时使用 connect-multiparty 和 multer?并且您已将 multer 设置为使用内存作为存储机制 - 这意味着 req.file 将是一个缓冲区,而不是具有路径字段的对象。应该只是const upload = multer({dest:'uploads/'});
  • 我想通了。这个问题可以结束了。我可以从 react 上传图片到 express。我会尽快发布答案。

标签: javascript reactjs express cloudinary


【解决方案1】:

检查您在 /upload 中发送的数据。 它看到 req.file 是未定义的。

【讨论】:

  • 是的,它未定义,我知道为什么。
猜你喜欢
  • 2015-11-22
  • 1970-01-01
  • 1970-01-01
  • 2021-12-29
  • 2018-02-26
  • 1970-01-01
  • 2015-05-25
  • 2021-12-31
  • 2021-11-24
相关资源
最近更新 更多