【问题标题】:React JS file uploadReact JS文件上传
【发布时间】:2018-04-10 12:03:37
【问题描述】:

我正在尝试上传单个图像文件并将其路径保存到数据库中。但是,当我尝试发送上传的图片时(它们的详细信息保存在应用程序的状态中),关于发送的图片,请求的有效负载是空的。

这是我的组件:

    renderForm() {
        return (
            <div>
                <form onSubmit={ this.handleSubmit }>
                    <div className="uniform">
                        <div className="12u 12u%(medium)">
                            <ImageUploader 
                                withIcon={ true }
                                buttonText='Upload'
                                onChange={ this.onDrop }
                                imgExtension={ ['.jpg', '.png'] }
                                maxFileSize={ 6291456 }
                            />
                        </div>
                    </div>
                </form>
                <input /*onClick={ this.handleSubmit }*/ type="submit" value="Submit" />
            </div>
        );
    }

这是我的 onDrop 处理程序:

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

还有句柄提交:

handleSubmit(event) {
    event.preventDefault();
    console.log(this.state.images) // at this point, the list of files is populated, as present in the image below.
    axios.post('http://127.0.0.1/scoala-de-iarna/api/web/api/create-sponsor', {
        name: this.state.name,
        images: this.state.images
    });
}

这是要上传的文件列表。

这是请求的数据。

更新 - actions 文件夹中的 createSponsor 函数:

export function createSponsor(values) {
    return async (dispatch, getState) => {
        await axios({
            url: `${ROOT_URL}api/create-sponsor`,
            method: 'post',
            data: {
                name: values.name,
                images: values.images
            }
        })//.then((response) => dispatch(dispatchCreateSponsor(response)));
        .then(response => console.log(response))
    }
}

【问题讨论】:

    标签: javascript reactjs axios


    【解决方案1】:

    我在您的代码中没有看到任何promises。当你上传你的图片时,因为这个过程是异步的,你应该使用promisesasync await 并且当promise 被解决时,使用axios 发送你的post 请求。

    handleUpload() { return newPromise((resolve, reject) =&gt; { ... }) }

    handleUpload.then( (res) => { // make your post request }, (rej) => { // handle rejection} );

    Here你有一个准确的例子,也许它会帮助你。

    【讨论】:

    • 我写了一个动作,使用 async wait 和 axios。我已经用我之前提到的动作更新了这个问题。但即使使用 async - await 东西,它仍然会在请求负载中显示一个空的文件列表。
    猜你喜欢
    • 2021-09-13
    • 1970-01-01
    • 1970-01-01
    • 2017-10-22
    • 2020-09-02
    • 2020-07-16
    • 1970-01-01
    • 2021-08-29
    • 1970-01-01
    相关资源
    最近更新 更多