如何使用formdata在react-redux中发布图像并将其发送到nodejs

时间:2018-10-16 06:51:09

标签: node.js reactjs

我是React的新手,我还没有看过任何有关使用formdata上传图像的文档(react),而且我也无法在server(nodejs)上发送图像。堆栈图像上传

1 个答案:

答案 0 :(得分:0)

签出我的git存储库,其中包含图像上传react frontend和node.js服务器,以将图像上传到AWS S3存储桶。 https://github.com/ShanikaEdiriweera/image-upload-app

作为@NguyễnThanhTú答案和回购中使用的方法(从react组件调用http请求)的补充,这就是应该使用Redux和动作创建者(redux-thunk作为中间件)来处理副作用例如API /服务器调用。

组件代码:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as imageActions from '../actions/imageActions';
export default class WhatsApp extends Component {
    ...

    handleSubmit = e => {
        e.preventDefault();
        if (!this.fileInput.current.files[0]) return;
        let data = new FormData();
        data.append('logo', this.fileInput.current.files[0]);

        // calling the action creator
        this.props.imageActions.imageUpload(data);
    };

    ...
}

function mapDispatchToProps(dispatch) {
    return {
        imageActions: bindActionCreators(imageActions, dispatch),
        ...
    };
}

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(WhatsApp);

imageActions.js操作文件:

import axios from 'axios';
...
export const imageUpload = (data) => {
    return dispatch => {
        return axios.post('http://127.0.0.1:3100/what', data).then(
            // here we can dispatch redux actions
            // and then handle them in redux reducers
            res => console.log(res.data),
            err => console.log(err.message)
        );
    };
};

在内部动作创建器中,我们可以调度redux actions,然后在redux reducers中处理所调度的动作,以在前端组件上创建效果。

相关问题