【问题标题】:Req.files and req.files are defined定义了 Req.files 和 req.files
【发布时间】:2021-01-26 07:31:09
【问题描述】:

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

前端产品.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')
            )
            })

***后端产品.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)

有人帮忙,请卡住几天

【问题讨论】:

  • 控制台是否有任何错误?
  • 没有错误但前端正在接收:无法读取未定义的属性长度
  • 如果你传递一个普通的对象,Axios 不会上传文件。您需要向它传递一个 FormData 对象。
  • 当我控制台(req.files)时在后端得到一个空数组
  • @Quentin 感谢您的帮助。更改为 ` let data =new FormData() data.append('name',name); data.append('数量',数量); data.append('price',price);data.append('description',description); data.append('offer',offer); data.append('制造商',制造商); data.append('expiryDate', expiryDate); data.append('photos',photos) data.append('approved',approved); data.append('reviews',reviews); data.append('类别',类别); console.log(data) await axios.post('127.0.0.1:2000/api/product/create',data,headers) `

标签: javascript node.js reactjs multer


【解决方案1】:

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

谢谢

【讨论】:

    猜你喜欢
    • 2012-12-10
    • 1970-01-01
    • 1970-01-01
    • 2021-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-23
    • 1970-01-01
    相关资源
    最近更新 更多