【问题标题】:How to submit multipart/form-data from react to express?如何从反应提交多部分/表单数据到表达?
【发布时间】:2020-04-06 20:16:20
【问题描述】:

我正在尝试提交带有 ImageName 类别的表单。但是在我的 ExpressJS(后端)中,我无法获取数据。在快递中,我使用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 我得到{ }。请告诉我如何发送带有文本数据的图片来表达

注意:如果我只从反应中传递数据(不是图像),比如说data: {name: 'Shivam'},那么我将在后端获取它。

【问题讨论】:

    标签: node.js reactjs express react-router axios


    【解决方案1】:

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

    快递Js: 在 express 中将 base64 转换为图像(img,pdf,xlxs,etc...)

        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) {
    
        }
    

    【讨论】:

    • 非常感谢分享代码。我将尝试在我的项目中实施。如果我遇到任何困难,我会回复你。
    猜你喜欢
    • 2013-03-06
    • 2017-02-04
    • 2022-01-07
    • 2017-06-01
    • 1970-01-01
    • 2020-08-22
    • 1970-01-01
    • 2012-06-16
    • 1970-01-01
    相关资源
    最近更新 更多