从图像上传到快速表达

时间:2020-06-16 20:33:13

标签: node.js reactjs express multer

从反应状态上传图像以表达时,我遇到了问题。 发送图像时,我的快速路线中出现空数组。但是文本在后端发送和接收都没有问题。问题是图像没有发送到后端。

这是我的React代码:

import React, { Component } from 'react'
import ImageUploader from 'react-images-upload'
import API from '../../../../api'

export default class AddCategory extends Component {

    constructor(props) {
        super(props);
        this.state = {
            formData: {
                name_uz: '',
                name_ru: '',
                name_en: ''
            },
            pictures: [],
            response: false,
            loading: false,
            responseText: '',
            responseResult: false
        }
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
        this.clearForm = this.clearForm.bind(this);
        this.onDrop = this.onDrop.bind(this);
    }

    onDrop(picture) {
        this.setState({
            pictures: this.state.pictures.concat(picture),
        });
    }

    handleChange = e => {
        let state = (this.state); 
        let a = state.formData;
        a[e.target.name] = e.target.value;
        this.setState({formData: a});
    }

    handleSubmit = e => {
        e.preventDefault()
        this.setState({ loading: true })

        const texts = this.state.formData
        const pictures = this.state.pictures
        console.log(pictures)
        const postData = {texts, pictures}

        API.post(`/content/category/new`, {postData})
          .then(res => {
                this.setState({ responseText: res.data.text })
                res.data.status ? this.setState({ loading: false, responseResult: true, response: true }) : this.setState({ loading: false, responseResult: false, response: true })

            this.clearForm()

            setTimeout(function () {
              this.setState({response: false});
            }.bind(this), 6900)
        })

    }

    render() {
        return (
          <div className='content-manager-section'>
           <Form onSubmit={this.handleSubmit}>
                                <ImageUploader
                                    withIcon={true}
                                    buttonText='Выберите изображения'
                                    onChange={this.onDrop}
                                    imgExtension={['.jpg']}
                                    maxFileSize={5242880}
                                    label='Максимальный размер изображения: 2 Мб, Тип изображения: .jpg'
                                    fileSizeError='Файл слишком большой файл'
                                    fileTypeError='Недопустимый тип файла'
                                    singleImage={true}
                                />

                                  <input onChange={this.handleChange} value={this.state.formData.name_uz} maxLength='50' name='name_uz' placeholder='Название' />
                                  <input onChange={this.handleChange} value={this.state.formData.name_ru} maxLength='50' name='name_ru' placeholder='Название' />
                                  <input onChange={this.handleChange} value={this.state.formData.name_en} maxLength='50' name='name_en' placeholder='Название' />

                                        <Button className={this.state.loading ? 'loading submit-btn' : 'submit-btn'} type='submit'><i className='lnil lnil-cloud-upload'></i>Добавить</Button>


          </Form>
        </div>
        )
    }
}

这是我的Express代码:

const uuidv4 = require('uuid')
const multer = require("multer")

const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, DIR);
    },
    filename: (req, file, cb) => {
        const fileName = file.originalname.toLowerCase().split(' ').join('-');
        cb(null, uuidv4() + '-' + fileName)
    }
});

var upload = 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!'));
        }
    }
});

.post('/new', upload.single('image'), (req, res) => {

        console.log(req.body)
        console.log(req.files)
})

这是Express在控制台中登录的内容

{
   postData: {
     texts: { name_uz: '', name_ru: '', name_en: '' },
     pictures: [ {} ]
   }
}
undefined

请让我知道我的错误步骤。

修改

内部状态中的方括号[]似乎有些奇怪的行为。每当我在状态中使用[]并尝试将其发布时,发送的数组都是空的。

1 个答案:

答案 0 :(得分:0)

我自己解决了。我必须使用FormData接口发送文件。 如果有人需要它,here是文档。

在Express中,我使用multer字段来接收图片和文本。

我的React代码有效的示例:

        const formData = new FormData();
        for (var i = 0; i < this.state.pictures.length; i++) {
            formData.append('categorypic', this.state.pictures[i])
        }
        formData.append('texts', JSON.stringify(this.state.formTexts))

        axios.post('your_url_here', formData)
            .then(res => {

            })