【问题标题】:How to upload a file (Laravel)如何上传文件(Laravel)
【发布时间】:2018-01-09 10:34:33
【问题描述】:

我想在 Laravel 中上传文件:

  1. 我把这段代码放在路由中

    Route::post('upload', 'myconttest@test')->name('upload');
    
  2. 并将这段代码放入控制器中

    function test(Request $request){
        $file=$request->file('myfile');
        $filename=$file->getClinetOriginalName();
        //  $projectname;
        $path='files/';
        $file->move($path,$filename);
    }
    

我在公共文件中创建了一个文件夹。代码运行没有错误,但文件没有保存。

【问题讨论】:

  • 变量 $file 的转储显示什么?
  • 你的表单有enctype="multipart/form-data"属性,否则表单不接受文件
  • 这是我的表单
  • 不幸的是它没有用

标签: php html database laravel


【解决方案1】:
  1. 确保您的表单已启用上传文件。因此,请检查是否设置了以下属性。

    <form action"" 'files' => true>

  2. 使用以下命名空间

    use Illuminate\Support\Facades\Input;

  3. 然后试试这个:

    $file = Input::file('myfile'); $filename = $file->getClinetOriginalName(); move_uploaded_file($file->getPathName(), 'your_target_path/'.$filename);

【讨论】:

    【解决方案2】:

    这是一个工作代码,请看这个

     public function store(Request $request)
        {
    
             $checkval = implode(',', $request->category);
             $input = $request->all();
             $input['category'] = $checkval;
    
             if ($request->hasFile('userpic')) {
              $userpic = $input['pic'];
              $file_path = public_path("avatars/$userpic");
              if(File::exists($file_path)) {
                  File::delete($file_path);
              }
              $fileName = time().$request->userpic->getClientOriginalName();
              $request->userpic->move(public_path('avatars'), $fileName);
              $input['userpic'] = $fileName;
              Product::create($input);
              return redirect()->route('productCRUD.index')->with('success','Product created successfully');
           }    
        }
    

    【讨论】:

    • 你弄错了它的工作代码我检查了很多次,首先你必须检查 $request ->all() by print_r()
    【解决方案3】:

    我想你可以试试这个:

    首先你给公用文件夹中的文件夹权限

    function test(Request $request){
        $file=$request->file('myfile');
        $filename=$file->getClinetOriginalName();
        $file->move(public_path().'/files/', $filename);
    }
    

    希望这对你有用!!!

    【讨论】:

      【解决方案4】:

      在控制器测试功能中,您需要给出文件夹的公共路径,例如

      $path = public_path('files/');
      

      用于在给定的公用文件夹路径上移动文件。

      【讨论】:

      • 对不起,我在 public_path() 中的错误,它需要一个文件夹路径作为参数
      猜你喜欢
      • 2019-03-18
      • 1970-01-01
      • 2014-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-29
      • 2021-10-18
      • 1970-01-01
      相关资源
      最近更新 更多