如何将图像上传到Laravel存储



我正在尝试实现关于如何将图像上传到laravel storage的指南,但当我提交时,它显示页面已过期。log中没有错误报告,这使得调试变得困难。

web.php

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

StorageController.php

<?php
namespace AppHttpControllers;
use IlluminateHttpRequest;
use AppModelsImage;
use AppModelsPhoto;

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 AppModels;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
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

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

您应该在表单标记中包含@csrf

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

相关内容

  • 没有找到相关文章

最新更新