我正试图向api发出一个post请求,以上传用户图像并将其发送到api进行配置文件设置。但我总是收到";需要图像字段";虽然我发送了formData对象,但还是出现了错误。以下代码中的错误在哪里?请帮忙。下面是我的代码。Get请求工作正常,但post请求不工作
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>
);
}
我们使用的是axios版本0.25或0.26,解决方案是
axios.post(url, formData, {
headers: { 'Content-Type': 'multipart/form-data' },
transformRequest: formData => formData,
})
从axios 0.27版本开始,它可以正常工作。