我在我的Laravel(5.4)网站上有一个上传头像部分,如果用户还没有上传头像,根据他们的性别,它会显示男性或女性"默认"头像,
一切正常,并且上传一个新的工作正常,但上传新的头像时,它会删除或覆盖默认头像
(我的用户控制器)
public function update(Request $r)
{
$this->validate($r, [
'location' => 'required',
'about' => 'required|max:355'
]);
Auth::user()->profile()->update([
'location' => $r->location,
'about' => $r->about
]);
return back()->with('msg', 'Profile successfully edited');
$user = User::find(Auth::user()->id);
// Handle the user upload of avatar
if ($r->hasFile('avatar')) {
$avatar = $r->file('avatar');
$filename = time() . '.' . $avatar->getClientOriginalExtension();
Image::make($avatar)->resize(300, 300)->save('uploads/avatars/' . $filename);
$user = Auth::user();
$user->avatar = $filename;
$user->save();
}
// Delete current image before uploading new image
if ($user->avatar !== 'man.png' || 'woman.png') {
//$file = public_path('uploads/avatars/' . $user->avatar);
$file = 'uploads/avatars/' . $user->avatar;
//$destinationPath = 'uploads/' . $id . '/';
}
if (File::exists($file)) {
unlink($file);
}
return back()->with('msg', 'Profile successfully edited');
}
}
在我的RegisterController中我有
protected function create(array $data)
{
if($data['gender']){
$avatar = 'man.png';
}
else{
$avatar = 'woman.png';
}
在我的(个人资料)edit.blade.php
中<form enctype="multipart/form-data" action="{{ route('profile.update') }}"
method="post">
{{ csrf_field() }}
<div class="form-group">
<label for="avatar" >Change Avatar</label>
<input type="file" name="avatar" class="form-control" accept="image/*">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
</div>
我想保持男性和女性.png文件不受影响,有人可以解释我在这里做错了吗?
答案 0 :(得分:1)
if语句不起作用的原因是因为while (cursor.moveToNext()) {
SqlContact contact = new SqlContact();
contact.setId((cursor.getString(0)));
contact.setDescription(cursor.getString(1));
contact.setMessage(cursor.getString(2));
contact.setStatus(cursor.getString(3));
contact.setTimestamp(cursor.getString(4));
contact.setType(cursor.getString(5));
contactList.add(contact);
}
将评估为'woman.png'
所以你的if语句基本上是:
true
始终为if ($user->avatar !== 'man.png' || true)
。
将您的if语句更改为:
true
希望这有帮助!
答案 1 :(得分:0)
好的,
我让它像
一样工作$user = User::find(Auth::user()->id);
// Handle the user upload of avatar
if ($r->hasFile('avatar')) {
$avatar = $r->file('avatar');
$filename = time() . '.' . $avatar->getClientOriginalExtension();
}
// Delete current image before uploading new image
if ($user->avatar !== 'man.png' && $user->avatar !== 'woman.png')
$file = 'uploads/avatars/' . $user->avatar;
if (File::exists($file)) {
unlink($file);
}
Image::make($avatar)->resize(300, 300)->save('uploads/avatars/' .
$filename);
$user = Auth::user();
$user->avatar = $filename;
$user->save();
return back()->with('msg', 'Profiel is bijgewerkt');
}
}