NodeJS 我尝试将图像文件发送到后端服务器,但当它到达时,我收到一个空对象

6rqinv9w  于 2023-01-30  发布在  Node.js
关注(0)|答案(2)|浏览(96)

我试图使一个形式,采取图像发送到后端,并保存在我的本地磁盘,但当我发送我的图像文件到后端,它显示一个空对象。
前端

import Axios from 'axios'
import { useForm } from 'react-hook-form'

const Create_post = () => {

    const { register, handleSubmit } = useForm()

    const onSubmit = (data) => {
        let post = {
            file:data.image[0]
        }
        handleApi(post)
    }

    const handleApi = (post) => {

        console.log(post)

        Axios.post('http://localhost:3001/api/post', post).then((response) => {
            console.log(response)
        })
    }

    return (  
        <div>
            <form onSubmit={handleSubmit(onSubmit)}>      
                <input type='text'/>
                <div>
                    <div>
                        <div>
                            <input type='file' name='fileInput' {...register(
                                'image', {required: true}
                            )}/>
                        </div>
                    </div>
                </div>
                <input type='submit' name='submitButton'/>      
            </form>
        </div>
    );
}
 
export default Create_post;

后端

const express = require('express')
const app = express()
const cors = require('cors')
const sql = require('mysql')
const bodyParser = require('body-parser')
const imgUpload = require('express-fileupload')

const db = sql.createPool({
    host:'localhost',
    user:'root',
    password:'password',
    database:'photo_website_database'
})

app.use(cors())
app.use(express.json())
app.use(bodyParser.urlencoded({extended:true}))
app.use(imgUpload())

app.post('/api/post/', (req, res)=>{
    let post = req.body
    console.log(post.file)
})

app.listen(3001,()=>{
    console.log('running on port 3001')  
})

...............................................................................................

yyyllmsg

yyyllmsg1#

如果要发送文件,则必须将其作为formData发送。
将数据转换为formData,然后发送。
此外,您的内容类型应该是multipart/form-data,但我认为当您向axios给予formData时,它会自动为您添加该头
您可以在线找到如何将对象转换为formData Convert JS Object to form data

gev0vcfq

gev0vcfq2#

文件通过表单数据从前端发送到后端要使用axios发布FormData,您需要在标题中指定您正在发送FormData,因为content-type应该是multipart/form-data
检查这个,如何使用FormData与axios:

let formData = new FormData();    //formdata object

formData.append('name', 'ABC');   //append the values with key, value pair
formData.append('age', 20);

    const config = {     
        headers: { 'content-type': 'multipart/form-data' }
    }

axios.post(url, formData, config)
    .then(response => {
        console.log(response);
    })
    .catch(error => {
        console.log(error);
    });

要上传图像文件,您可以按照以下指南教程操作:Upload files images in react using axios
在后端,您可以使用req.files来获取文件,而不是req.body

app.post('/api/post/', (req, res)=>{
    let image = req.files;
    console.log("Image :", image);
})

相关问题