2013-09-27 92 views
22

我有一个表单,其中包括其他信息,用户可以上传图像。我想将路径存储在数据库中的图像上,并将图像保存到服务器上的public/img/文件夹中。 {{ Form::open(['route'=>'pizzas.store', 'files'=>true]) }},以便它能够将文件发布:Laravel 4 - 文件上传

的形式使用打开。检查HTML我有以下内容:

<form method="POST" action="http://mypizza/pizzas" 
    accept-charset="UTF-8" enctype="multipart/form-data"> 

我可以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 
} 

当我选择一个文件并提交表单,一切似乎工作,但没有文件被保存在文件夹/img。数据库正确注册文件路径和名称。在if { ...}块之后

运行dd($uploadSuccess);正确的,我得到如下:

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" } 

我在做什么错?

+3

除了从[Reflic]答案,则有必要调整数据库上的'path'如下:''路径'=>'img /'。 $ filename]);' –

+0

那是正确的,我已经忘记了这一点。 – Reflic

回答

33

$ destination_path可是错误的。您必须在您的变量$目的地像这样的路径/ public目录:

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

3

既然你似乎是使用PHP 5.4,你也可以考虑使用Stapler。它现在非常稳定(很快就会超出测试版),并且可以为您节省大量现在不得不编写的样板文件。通过@Reflic给出

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

答案可能BR权......但不适合我....
这条道路为我工作。
它可能是因为我从url中删除“public /”... 谢谢。

1

我有同样的问题。我把一切都说得对,我的代码除了

public_path() 

没有预先考虑到我的文件夹

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

我也这样做是为了改变我的文件名

我得到的文件扩展名

$extension = Input::file('YourFileName')->getClientOriginalExtension(); 
$filename = WhateverYouWantHere . '.' . $extension; 

,就是这样,文件名更改。 Laravel确实很棒

1

你也可以写相对路径。 等作为

$destinationPath="resources/assets/images/";

$destinationPath= 'public/img/';