将头像图像添加到Profile Laravel 5

问题描述 投票:2回答:1

我想建立一个个人资料图片头像上传并在每个用户的个人资料中显示它。

但是不能使用我的方法。

我的头像上传代码:

<div class="form-group">
        <div class="form-group">
          <label for="exampleInputFile"><img src="/img/photos.png" height="80" width="80"> Upload Avatar:</label>
          <input type="file" id="exampleInputFile" name="profileimage"></font></br>

        </div>
      </div>

每个人在个人资料中看到的代码:

      <div class="pull-left margin-left-25">
@if($user->profileimage == false) 
<img src="/img/icon.png"  height="80" width="80">
@endif
@if($user->profileimage == true) 
<img src="{{$user->profileimage}}" height="80" width="80">
@endif

ProfileController图像内容(不适合我):

if ($request->hasFile('image')) {

         $file = $request->file('profileimage');

         $size = $request->file('profileimage')->getSize();
         if ($size > 500000) {
           session()->flash('errormessage','Image is too large');
           return redirect()->back()->withInput();
         }
         if (substr($file->getMimeType(), 0, 5) !== 'profileimage') {
           session()->flash('errormessage','File is not an image');
           return redirect()->back()->withInput();
         }

        if ($file->isValid()) {
            $path = $request->profileimage->store('uploads','public');
        } else {

          session()->flash('errormessage','Image is not valid');
          return redirect()->back()->withInput();
        }

      }



     if ($request->image !== null) {
            $product->image = $path;
          }

我做错了什么?

谢谢!

laravel laravel-5
1个回答
1
投票

为什么不使用Validator类?它比你编码的更容易。如下,

$this->validate($request, [
    'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:500000',
]);

在存储文件的方法中添加上述代码并执行操作。

它将为您进行验证,然后继续您想要对文件执行的任何操作。有关更多选项,请查看提供的链接。

另外,在您的HTML代码中。您需要首先拥有一个表单,操作及其方法,因此您的代码应该是:

<div class="form-group">
        <div class="form-group">
          <form action="{{ route('profile'}}" method="post">
          <label for="exampleInputFile"><img src="/img/photos.png" height="80" width="80"> Upload Avatar:</label>
          <input type="file" id="exampleInputFile" name="profileimage"></font></br>
          </form>
        </div>
</div>

在你的web.php中,你应该有以下几行:

Route::get('/URL', 'ProfileController@MethodName')->name('profile');
© www.soinside.com 2019 - 2024. All rights reserved.