简体   繁体   English

如何上传文件(Laravel)

[英]How to upload a file (Laravel)

I want to upload a file in Laravel: 我想在Laravel中上传文件:

  1. I put this code in route 我将此代码放在路线中

     Route::post('upload', 'myconttest@test')->name('upload'); 
  2. And put this code in controller 并将此代码放入控制器

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

I create a folder in public called files. 我在公共文件夹中创建了一个文件夹。 The code runs without error but the file is not saved. 该代码运行无错误,但文件未保存。

  1. Make sure your form is enabled to upload the file. 确保您的表单已启用以上传文件。 So check that the following attribute is set or not. 因此,请检查是否设置了以下属性。

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

  2. Use the following namespace 使用以下名称空间

    use Illuminate\\Support\\Facades\\Input;

  3. Then try this: 然后试试这个:

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

Its a working code please see this 它的工作代码请看这里

 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');
       }    
    }

I think you can try this: 我认为您可以尝试以下方法:

First you give folder permission to files folder in public folder 首先,您将文件夹权限授予公用文件夹中的文件文件夹

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

Hope this work for you !!! 希望这项工作为您服务!

In controller test function you need to given public path of files folder like 在控制器测试功能中,您需要指定文件文件夹的公共路径,例如

$path = public_path('files/');

for moving file on given public folder path. 用于在给定的公用文件夹路径上移动文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM