【问题标题】:The post method is not supported for this route. Supported methods: get, head Laravel 8此路由不支持 post 方法。支持的方法:get、head Laravel 8
【发布时间】:2021-05-08 15:24:32
【问题描述】:

我正在尝试为用户帐户开发文件上传。每次提交时,我都会收到错误消息:此路由不支持 POST 方法。支持的方法:GET、HEAD。

但它应该支持Post方法吗?

你能帮忙吗?

<form  action="{{url('image-upload')}}" enctype="multipart/form-data" method="post">
     @csrf
     <input type="file" name="file">
     <input type="submit">
</form>

控制器

 <?php

namespace App\Http\Controllers;

use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\View\Factory;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

class ImageUploadController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return Application|Factory|View
     */
    public function imageUpload()
    {
        return view('imageUpload');
    }

    /**
     * Display a listing of the resource.
     *
     * @param Request $request
     * @return RedirectResponse
     */
    public function imageUploadPost(Request $request): RedirectResponse
    {
        $request->validate([
            'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ]);

        $imageName = time().'.'.$request->image->extension();

        $request->image->move(public_path('images'), $imageName);

        return back()
            ->with('success','You have successfully upload image.')
            ->with('image',$imageName);

    }
}

路由,web.php

    Route::get('image-upload', 'ImageUploadController@imageUpaload')->name('image.upload');
    Route::post('image-upload', 'ImageUploadController@imageUploadPost')->name('image.upload.post');

【问题讨论】:

  • 不用修改刀片代码,问题是缓存造成的,运行php artisan route:clear即可解决此问题

标签: laravel


【解决方案1】:

在您的表单中,您使用的是带有 GET 方法的路由,而不是带有 POST 方法的路由。您还使用函数 url 而不是路由。而不是image-upload,它应该是image.upload,带有一个点.

所以,您应该将action="{{url('image-upload')}}" 更改为action="{{route('image.upload.post')}}"

您的表单应该是这样的:

<form action="{{route('image.upload.post')}}" enctype="multipart/form-data" method="post">
     @csrf
     <input type="file" name="file">
     <input type="submit">
</form>

【讨论】:

  • 尝试使用php artisan route:clear清除路由缓存,然后重试。
  • 我没有定义这条路线 [image-upload.post]。 (查看:C:\xampp\htdocs\new_web\new_web\resources\views\home.blade.php)
  • {{ route('image.upload.post') }} 使用带点的路线名称。 :)
  • @Takachi 编辑了答案以反映这一点
  • 太棒了!谢谢你。现在我没有错误了,但是那个表单没有上传文件,只是刷新页面,就是这样..
猜你喜欢
  • 2020-06-05
  • 2020-04-19
  • 2020-01-22
  • 2020-04-25
  • 1970-01-01
  • 2019-08-28
  • 2019-08-31
  • 2021-05-05
相关资源
最近更新 更多