Laravel上传图片“控制器”

时间:2019-09-18 09:28:03

标签: laravel image upload

我正在关注this tutorial,以便在Laravel中上传图片。

它说:“成功创建控制器后,转到app / controllers / ImageController.php并输入以下代码:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Validator,Redirect,Response,File;

class ImageController extends Controller
{

    public function index()
    {
        return view('image');
    }

    public function save()
    {
       request()->validate([
            'fileUpload' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
       ]);
       if ($files = $request->file('fileUpload')) {
           $destinationPath = 'public/image/'; // upload path
           $profileImage = date('YmdHis') . "." . $files->getClientOriginalExtension();
           $files->move($destinationPath, $profileImage);
        }
        return Redirect::to("image")
        ->withSuccess('Great! Image has been successfully uploaded.');

    }
}

但是,我的代码编辑器在此行中检测到单词request的错误

 if ($files = $request->file('fileUpload')) {

有人知道为什么吗?

3 个答案:

答案 0 :(得分:1)

如果要使用变量$request,则需要将其作为参数注入方法。

否则,请像进行验证一样使用助手request()

public function save()
{
   request()->validate([
       'fileUpload' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
   ]);
   if ($files = request()->file('fileUpload')) {
       $destinationPath = 'public/image/'; // upload path
       $profileImage = date('YmdHis') . "." . $files->getClientOriginalExtension();
       $files->move($destinationPath, $profileImage);
    }
    return Redirect::to("image")->withSuccess('Great! Image has been successfully uploaded.');
}

使用变量$request

public function save(Request $request)
{
   $request->validate([
       'fileUpload' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
   ]);
   if ($files = $request->file('fileUpload')) {
       $destinationPath = 'public/image/'; // upload path
       $profileImage = date('YmdHis') . "." . $files->getClientOriginalExtension();
       $files->move($destinationPath, $profileImage);
    }
    return Redirect::to("image")->withSuccess('Great! Image has been successfully uploaded.');
}

答案 1 :(得分:0)

您可以使用此

public function save(Request $request)
{
   $request->validate([
       'fileUpload' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
   ]);
   if ($files = $request->file('fileUpload')) {
       $destinationPath = 'public/image/'; // upload path
       $profileImage = date('YmdHis') . "." . $files->getClientOriginalExtension();
       $files->move($destinationPath, $profileImage);
    }
    return Redirect::to("image")->withSuccess('Great! Image has been successfully uploaded.');
}

因为您没有在这样的函数中传递类型提示

public function save(Request $request) 

答案 2 :(得分:0)

检查您是否忘记了在表单中添加enctype="multipart/form-data" <form action="{{url('dev/tester')}}" method="post" enctype="multipart/form-data">