使用 Axios Post 请求上传图片
我正在尝试向 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我们使用的是 axios 版本 0.25 或 0.26,解决方案
来自 axios 版本 0.27,它可以正常工作。
those we are using axios version 0.25 or 0.26, solution is
from axios version 0.27, it works as usual.