【发布时间】:2015-12-17 19:30:40
【问题描述】:
我有一个接受个人资料照片图像的表单。我知道该表单正在工作,就其他字段而言,但似乎该文件甚至没有被发布。如您所见,当我回显输入时,我得到了空值。这是我第一次处理文件上传,所以我可能遗漏了file 输入 POST 的方式。
这是在 profile.blade.php 中打开的表单
{!! Form::open(['id' => 'editUserProfileForm', 'class' => 'card', 'files' => true]) !!}
这是 profile.blade.php 中的表单输入
<div class="form-group m-b-20">
<span class="form-group-addon"><i class="zmdi zmdi-account"></i></span>
<label for="profile_pic">Profile Photo</label>
<input type="file" id="profile_pic" name="profile_pic" class="form-control">
</div>
这是带有验证等的控制器方法。如果您看到更简洁的方式来做我正在做的事情,我会很乐意接受建议。
public function postEditProfile($id)
{
$user = User::find($id);
$user_information = [
'name' => Input::get('name'),
'email' => Input::get('email'),
'password' => Input::get('password'),
'password_confirmation' => Input::get('password_confirmation'),
'profile_pic' => Input::file('profile_pic'),
];
$validator = Validator::make($user_information, [
'name' => 'required',
'email' => ($user_information['email'] != $user->email) ? 'required|unique:users' : 'required',
'password' => (! empty($user_information['password'])) ? 'min:6' : '',
'password_confirmation' => (! empty($user_information['password'])) ? 'same:password' : '',
'profile_pic' => (! empty($user_information['profile_pic'])) ? 'mimes:jpeg,bmp,png' : '',
]);
if($validator->fails()) {
echo json_encode(['st' => 0, 'msg' => $validator->errors()->all()]);
} else {
($user->name != $user_information['name']) ? $user->name = $user_information['name'] : false;
($user->email != $user_information['email']) ? $user->email = $user_information['email'] : false;
(! empty($user_information['password'])) ? $user->password = bcrypt($user_information['password']) : false;
if(! empty($user_information['profile_pic'])) {
$profile_pic_destination = 'profile_img';
$profile_pic_name = rand(11111111, 99999999) . '.' . $user_information['profile_pic']->getClientOriginalExtension();
$user_information['profile_pic']->move($profile_pic_destination, $profile_pic_name);
$user->photo = $profile_pic_name;
}
if($user->save()) {
//echo json_encode(['st' => 1, 'msg' => 'Your profile was saved successfully. Boom.']);
echo json_encode(['st' => 1, 'msg' => $user_information['profile_pic']]);
} else {
echo json_encode(['st' => 0, 'msg' => 'The user was not updated.']);
}
}
}
【问题讨论】:
-
作为旁注,我看到您正在使用 rand() 生成文件名,但仍有可能覆盖文件。我建议给文件加上时间戳。或者至少检查文件不存在。
-
@ViperCode 谢谢!这是个好主意。
-
另外,您应该真正检查用户上传的内容是否真的是图像,而不是扩展名为 .jpg 的文件。用户可能会以这种方式上传脚本并在您的网站上造成严重破坏。这是一个相当简单的检查,请参阅:stackoverflow.com/questions/1581136/…
-
@ViperCode 这是另一个好建议。我相信我是通过 Laravel 的验证
mime:jpg,bmp,png来做到这一点的。 -
尝试 dd(Input::file('field_name')) 如果出现任何结果,则文件已发布。