Laravel 4 - 文件上传

Geo*_*era 22 php file-upload laravel laravel-4

我有一个表单,除了其他信息,用户将上传图像.我想在数据库中存储图像的路径,并将图像保存到public/img/服务器上的文件夹中.

使用以下命令打开表单:{{ Form::open(['route'=>'pizzas.store', 'files'=>true]) }}以便能够POST文件.检查HTML我有以下内容:

<form method="POST" action="http://mypizza/pizzas" 
  accept-charset="UTF-8" enctype="multipart/form-data">
Run Code Online (Sandbox Code Playgroud)

我可以POST到我的控制器并按预期从表单接收所有数据.处理文件的方法如下:

public function store() {
    //TODO -  Validation

    $destinationPath = '';
    $filename        = '';

    if (Input::hasFile('image')) {
        $file            = Input::file('image');
        $destinationPath = '/img/';
        $filename        = str_random(6) . '_' . $file->getClientOriginalName();
        $uploadSuccess   = $file->move($destinationPath, $filename);
    }


    $pizza = Pizza::create(['name'       => Input::get('name'),
                           'price'       => Input::get('price'),
                           'ingredients' => Input::get('ingredients'),
                           'active'      => Input::get('active'),
                           'path'        => $destinationPath . $filename]);

    if ($pizza) {
        return Redirect::route('pizzas.show', $pizza->id);
    }

    //TODO - else
}
Run Code Online (Sandbox Code Playgroud)

当我选择一个文件并提交表单时,一切似乎都有效,除了文件/img夹中没有保存文件.数据库正确注册文件路径和名称.

dd($uploadSuccess);if { ...}块之后运行,我得到以下内容:

object(Symfony\Component\HttpFoundation\File\File)#220 (2) {
  ["pathName":"SplFileInfo":private]=> string(17) "/img\YZmLw7_2.jpg"
  ["fileName":"SplFileInfo":private]=> string(12) "YZmLw7_2.jpg" }
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Ref*_*lic 33

你的$ destination_path是错误的.您必须在变量$ destination中包含/ public目录的路径,如下所示:

$destinationPath = public_path().'/img/';