Home > database >  I am trying to send a image file to my backend server but when it arrives I receive an empty object
I am trying to send a image file to my backend server but when it arrives I receive an empty object

Time:01-28

I am trying to make a form that takes an image sends it to the backend and saves it on my local disk but when I send my image file to the backend it displays an empty object.

Frontend

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;

Backend

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

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

CodePudding user response:

If you are sending a file, you have to send it as formData.

Convert your data into formData then send.

Also your content type should be multipart/form-data, but I think axios will add that header automatically for you when you give him formData

You can find online how to convert object into formData Convert JS Object to form data

CodePudding user response:

Files are sent through form data from frontend to backend To post the FormData using axios, you need specify in header that you are sending FormData, for that content-type should be multipart/form-data.

Check this, how to use FormData with 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);
    });

For uploading the images file you can follow this guide tutorial: Upload files images in react using axios

And in the backend you can use the req.files to get the files not the req.body

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