我正在使用 React 和 Laravel 构建一个注册表单,我想允许用户上传个人资料图片。我有两个组件,一个用于注册表单,另一个用于主页组件。我正在使用以下代码在注册组件中上传图片
<form enctype="multipart/form-data">
<input name="profile_image" placeholder="Profil Picture" type='file' onChange={handleFileChange}/>
</form>
home 组件中的代码
const [image, setImage] = useState(null);
function handleFileChange(event) {
setImage(event.target.files[0]);
}
const formData = new FormData();
formData.append('image', image);
const signup = ev => {
ev.preventDefault()
const payload = {
Name: nameRef.current.value,
Email: emailRef.current.value,
password: passwordRef.current.value,
password_confirmation: password_confirmation.current.value,
ville_id:ville_ref.current.value,
profil_picture:formData
}
console.log(payload);
AxiosClients.post('/signup', [payload,formData])
.then(({data}) => {
setcurrentUser(data.user);
Settoken(data.token);
})
.catch((err) => {
const response = err.response;
if (response && response.status === 422) {
Seterrors(response.data.errors);
}
// console.log(Erors.Name);
})
}
const login=(e)=>{
e.preventDefault();
const payload={
email:Emailref.current.value,
password:PassRef.current.value
}
AxiosClients.post('/login', payload)
.then(({data}) => {
// setcurrentUser(data.user);
// console.log(data.token);
Settoken(data.token);
})
.catch((err) => {
const response = err.response;
if (response && response.status === 422) {
console.log(response);
setMessage(response.data.message);
}
// console.log(Erors.Name);
})
}
控制器
$path = $request->file('image')->store('public/images');
/** @var \App\Models\User $student */
$user = User::create([
'name' => $data['Name'],
'email' => $data['Email'],
'ville_id'=>$data['ville_id'],
'profil'=>$data['profil'],
'password' => bcrypt($data['password']),
'profil_picture'=>$path,
]);
但是,当我尝试存储图像时,我存储了一个空值。有人可以帮我弄清楚我做错了什么吗?提前致谢!
看来问题可能与您将
formData
附加到有效负载的方式有关。在您的注册功能中,您正在创建一个新的 FormData
实例并将图像状态附加到它。但是,您随后将有效负载和 formData
作为数组传递给 AxiosClients.post
方法。这可能会导致数据发送到服务器的方式出现问题。
要解决此问题,您可以将
formData
直接附加到有效载荷对象,如下所示:
const payload = new FormData();
payload.append('Name', nameRef.current.value);
payload.append('Email', emailRef.current.value);
payload.append('password', passwordRef.current.value);
payload.append('password_confirmation', password_confirmation.current.value);
payload.append('ville_id', ville_ref.current.value);
payload.append('profil_picture', image);
在进行此更改之前,通过执行
dd($request->file('image'))
在控制器中检查它以验证之前和之后。