Upload Image with Axios Post Request

I am trying to make a post request to an api to upload a user image and send it to the api for profile settings.But i always receive "the image field is required" error although I send formData object. Where is my mistake in below codes ? Please help. below are my codes. Get request is working fine but post request is not working

src - api.js
export const updateProfileImage = (formData) => {
    return axios.post('/my/profile/image', formData, {
        headers: { 'Content-Type': 'multipart/form-data' },
    });
};
src - redux - extraActions.js
export const updateProfileImage = createAsyncThunk(
    'profileCreation/updateProfileImage',
    async (formData, { rejectWithValue }) => {
        return handleApiCall(() => getProfileApi.updateProfileImage(formData), rejectWithValue);
    },
);
src - redux - slice.js
import { createSlice } from '@reduxjs/toolkit';
import { updateProfileImage } from './extraActions';
import { REDUX_LOADING_STATUS } from '@constants/status';
import {
    applyFulfilledStatus,
    applyRejectedStatus,
    applyPendingStatus,
    errorMessage,
    successMessage,
} from '@utils/redux';

const initialState = {
    userInfo: {},
    status: REDUX_LOADING_STATUS,
    statusCode: '',
    message: '',
};

export const profileCreationSlice = createSlice({
    name: 'profile',
    initialState,
    reducers: {},
    extraReducers: (builder) => {
        builder.addCase(updateProfileImage.pending, (state) => {
            console.info('profile image is being sent to api...');
            applyPendingStatus(state);
        });

        builder.addCase(updateProfileImage.rejected, (state, action) => {
            applyRejectedStatus(state, action);
            errorMessage(action.payload.message);
        });

        builder.addCase(updateProfileImage.fulfilled, (state, action) => {
            applyFulfilledStatus(state, action);
            successMessage(action.payload.message);
        });
    },
});

export default profileCreationSlice.reducer;
src - containers- ProfileContainer - generalContainer - index.js
import React from 'react';
import { Row, Col, Button } from 'antd';
import styles from './index.module.less';
import { updateProfileImage } from '@redux/slices/profileCreation/extraActions';

export default function GeneralContainer() {
    const [profileImage, setProfileImage] = useState();


    function updateProfileImg(e) {
        e.preventDefault();
        const formData = new FormData();
        formData.append('profileImage', profileImage);
        dispatch(
            updateProfileImage({
                image: formData,
                // image is my api key
            }),
        );
    }
    return (
        <Row className={styles.rowGeneral}>
            <Col span={24} className={styles.subtitleCol}>
                <h4>Profile Settings</h4>
            </Col>
            <Col span={24}>
                <form onSubmit={updateProfileImg}>
                    <div className={styles.profileImage}>
                        <img
                            src={profileImage ? URL.createObjectURL(profileImage) : userInfo?.thumb}
                        />
                        <p>Profile Photo</p>
                    </div>
                    <label htmlFor="img" className={styles.uploadLabel}>
                        Upload a photo:
                    </label>
                    <input
                        type="file"
                        id="img"
                        name="img"
                        hidden
                        onChange={(e) => {
                            setProfileImage(e.target.files[0]);
                        }}
                    />
                    <input type="submit" />
                </form>
            </Col>
        </Row>
    );
}
1

1 Answer

those we are using axios version 0.25 or 0.26, solution is

axios.post(url, formData, {
  headers: { 'Content-Type': 'multipart/form-data' },
  transformRequest: formData => formData,
})

from axios version 0.27, it works as usual.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sarah Jenkins

Sarah Jenkins

Senior Technology Editor & AI Specialist

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.

Share this article
Twitter Facebook Pinterest