如何从React向Express提交multipart/form-data?

4
我想提交一个包含“图像”和“类别名称”的表单,但是在我的ExpressJS(后端)中无法获取数据。在express中,我使用了“express-fileupload”包。以下是我的代码,请帮助我解决这个问题。
前端(React-CategoryForm.js):
import axios from "axios";
import React, { Component } from "react";

class CategoryForm extends Component {

    constructor(props) {
        super(props);
        this.state = { name: '', file: '', fileName: '' };

        this.onChange = this.onChange.bind(this);
        this.onChangeImageHandler = this.onChangeImageHandler.bind(this);
        this.onCreate = this.onCreate.bind(this);
    }

    /** Methods */
    onChange = e => this.setState({ [e.target.name]: e.target.value });
    onChangeImageHandler = e => this.setState({ fileName: e.target.files[0].name, file: e.target.files[0] });
    onCreate = async e => {
        e.preventDefault();
        e.stopPropagation();

        const formData = new FormData();
        formData.append('name', this.state.name);
        formData.append('file', this.state.file);

        const url = 'http://localhost:4000/api/v2/categories';
        const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVkZTc3MDM0NTgxM2QyN2NmZDExMWE3ZSIsImVtYWlsIjoiaGFyc2hhQHNrcmVlbS5pbyIsImlhdCI6MTU3NTQ0ODc1OSwiZXhwIjoxNTc2MzEyNzU5fQ.7wxCmPhkzb0aaB4q9PBKmHAj1Klw1NQmp1nBI3NsRRI';

        axios({
            method: 'POST',
            url: url,
            headers: {
                Authorization: `Bearer ${token}`,
                ContentType: 'multipart/form-data'
            },
            body: formData
        })
        .then(res => this.setState({ name: '', file: '', fileName: '' }))
        .catch(err => console.log('Error - ', err));
    }

    /** Rendering the Template */
    render() {

        const { name, fileName } = this.state;

        return (
                <form onSubmit={this.onCreate}>
                    <input type="text" name="name" value={name} onChange={this.onChange} placeholder="New Category Name" />
                    <input type="file" name="file" onChange={this.onChangeImageHandler} />
                    <button type="submit">Add Category</button>
                </form>
        )
    }
}

export default CategoryForm;

后端(ExpressJS:server.js)

const express = require("express");
const bodyParser = require("body-parser");
const fileUpload = require("express-fileupload");

app.use(fileUpload());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.use('/api/v2/categories',
        (req, res, next) => { console.log(req.body); },
        require("./categoryRoute"));


req.body中,我得到了{ }。请告诉我如何将图像与文本数据一起发送到Express。
注意:如果我从React仅传递数据(而不是图像),例如data: {name: 'Shivam'},则会在后端收到它。
1个回答

1

React: 将您的媒体文件转换为base64字符串。

Express Js: 在express中将base64转换为图像(img,pdf,xlxs等...)

    var base64Data = req.body.file_data // base64 string
    var file_name='123.png';
    var file_dir = "assets/client_folios/"
    var fs = require("fs");
    if (!fs.existsSync('assets/')){
      fs.mkdirSync('assets/');
    }
    if (!fs.existsSync(file_dir)){
       fs.mkdirSync(file_dir);
    }
    var file_path="assets/client_folios/"+file_name

     var file_path="assets/client_folios/"+file_name
    fs.writeFile(file_path, base64Data, 'base64',async function(err) {

    }

非常感谢分享代码。我会尝试在我的项目中实现它。如果遇到任何困难,我会与您联系。 - Shivam Verma

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接