如何将图片上传到 Laravel 存储?

How to upload image to Laravel storage?

我正在尝试实现关于如何将图像上传到 laravel storageguide,但是当我提交时,它显示该页面已过期。 log 中没有错误报告,因此很难调试。

web.php:

Route::get('/upload-image', [StorageController::class, 'index']);
Route::post('/save', [StorageController::class, 'save']);

StorageController.php:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Image;
use App\Models\Photo;



class StorageController extends Controller
{
    public function index()
    {
        return view('image');
    }

    public function save(Request $request)
    {
        $validatedData = $request->validate([
            'image' => 'required|image|mimes:jpg,png,jpeg,gif,svg|max:2048',
        ]);

        $name = $request->file('image')->getClientOriginalName();
        $path = $request->file('image')->store('public');

        $save = new Photo;
        $save->name = $name;
        $save->path = $path;
        $save->save();

        return redirect('upload-image')->with('status', 'Image Has been uploaded');
    }
}

型号Photo.php:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Photo extends Model
{
    use HasFactory;
}

Laravel 查看上传图片 image.blade.php:

<!DOCTYPE html>
<html>
<head>
  <title>Laravel 8 Uploading Image</title>
  <meta name="csrf-token" content="{{ csrf_token() }}">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
  <div class="container mt-5">
    @if(session('status'))
      <div class="alert alert-success">
        {{ session('status') }}
      </div>
    @endif
    <div class="card">
      <div class="card-header text-center font-weight-bold">
        <h2>Laravel 8 Upload Image Tutorial</h2>
      </div>
      <div class="card-body">
        <form method="POST" enctype="multipart/form-data" id="upload-image" action="{{ url('/save') }}" >
          <div class="row">
            <div class="col-md-12">
              <div class="form-group">
                <input type="file" name="image" placeholder="Choose image" id="image">
                @error('image')
                <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
                @enderror
              </div>
            </div>
            <div class="col-md-12">
              <button type="submit" class="btn btn-primary" id="submit">Submit</button>
            </div>
          </div>
        </form>
      </div>
    </div>
  </div>
</body>
</html>

因此,当我导航到 localhost/upload-image 时,它会显示视图,我可以在输入表单中选择 file,但是一旦我单击提交按钮,页面就会导航到 /save 并显示没有日志条目的 419 | Page Expired。浏览器控制台显示:

POST http://127.0.0.1:8000/save 419 (unknown status)

您没有在表单请求中传递 @csrf 令牌:

<form method="POST" enctype="multipart/form-data" id="upload-image" action="{{ url('/save') }}" >
@csrf

请按照上面的代码示例通过,然后就可以了。