需要使用FormData对象将文件添加到表单数据中,并将其作为第二个参数传递给axios.post方法。
代码示例:
import axios from 'axios';
import { useFormik } from 'formik';
const MyComponent = () => {
const formik = useFormik({
initialValues: {
name: '',
avatar: null,
},
onSubmit: async (values) => {
const formData = new FormData();
formData.append('name', values.name);
formData.append('avatar', values.avatar);
try {
const response = await axios.post('/api/upload', formData);
console.log(response);
} catch (error) {
console.error(error);
}
},
});
return (
);
};