dousi6701 2018-08-25 18:10
浏览 186
已采纳

使用Laravel将文件上载移动到特定文件夹

I am having issues getting my image uploads to move to the proper folders. When I upload them they just dump into the main img folder instead of going to the specific subfolder.

Here is the code I have:

            $rental = new Rental;

            $rental->title = $request->title;
            $rental->name = $request->name;
            $rental->description = $request->description;

             if ($request->hasFile('image')) {
                $image = $request->file('image');
                $filename = time() . '.' . $image->getClientOriginalExtension();
                $path = public_path('img/rentals' . $filename);
                 Image::make($image)->save($path);

                 $rental->image = $filename;
                }               

            $rental->save();
  • 写回答

1条回答 默认 最新

  • douyi6290 2018-08-25 21:01
    关注

    You're missing a / in your $path. The following line...

    $filename = time() . '.' . $image->getClientOriginalExtension();
    

    will generate a string, something like 123456789.jpg. Then in the next line you're doing...

    $path = public_path('img/rentals' . $filename);
    

    which joins together img/rentals and 123456789.jpg, resulting in img/rentals123456789.jpg. Notice that . which concatenates two strings. You're then passing the resulting string to public_path which will refer to a folder in your public directory named img and a filename rentals123456789.jpg.

    To solve your problem you just need to stick a forward slash in between:

    $filename = time() . '.' . $image->getClientOriginalExtension();
    $path = public_path('img/rentals/' . $filename);
    

    which will result in a folder img/rentals inside your public path and a filename of 123456789.jpg.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?