gpt4 book ai didi

node.js - 如何从 React 提交 multipart/form-data 到 express?

转载 作者:行者123 更新时间:2023-12-04 17:31:24 24 4
gpt4 key购买 nike

我正在尝试提交包含类别的图像名称 的表单。但是在我的 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 中,我得到了 { }。请告诉我如何发送带有文本数据的图像来表达

注意:如果我只传递来自 React 的数据(不是图像),假设 data: {name: 'Shivam'} 然后我得到它在后端。

最佳答案

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

Express Js:快速将 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) {

}

关于node.js - 如何从 React 提交 multipart/form-data 到 express?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59321524/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com