使用 Axios Post 请求上传图片

发布于 2025-01-11 15:50:25 字数 3826 浏览 0 评论 0原文

我正在尝试向 api 发出发布请求以上传用户图像并将其发送到 api 进行配置文件设置。但尽管我发送 formData 对象,但我总是收到“图像字段是必需的”错误。下面代码中我的错误在哪里?请帮忙。下面是我的代码。获取请求工作正常,但发布请求不起作用

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

吹泡泡o 2025-01-18 15:50:25

我们使用的是 axios 版本 0.25 或 0.26,解决方案

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

来自 axios 版本 0.27,它可以正常工作。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文