Symfony2:无法将图像上传到数据库

时间:2016-05-08 13:44:56

标签: php html symfony

我正在尝试通过以下表单将新产品添加到我的数据库中:

<form id="add_product" method="post" action="{{ path('company_addp') }}">
        <span class="fa fa-times close" onclick="new_prod()"></span><br />
        <span>Add new product:</span>
        <div id="holder">

        </div>
        <label for="img" style="display:inline-block; color: #5eb5e0; cursor: pointer;">click here</label> to add a picture
        <input type="file" name="upload" id="img" style="display: none;" />
        <input type="text" placeholder="product name" name="name">
        <textarea placeholder="product description" name="desc"></textarea>
        <input type="text" placeholder="price" name="price"/>
        <input type="text" placeholder="quantity" name="qty" />
        <input type="text" placeholder="category" name="type" />
        <input type="submit" value="add product" />
    </form>

通过此控制器:

    public function addproductAction(Request $request){
        if($request->getMethod() == "POST"){
            $session = $request->getSession();
            $id = $session->get('id');
            $type = $session->get('type');
            if($type == "comp"){

                $em = $this->getDoctrine()->getManager();
                $prod = new Products();
                $prod->setName($request->get('name'));
                $prod->setCompany($id);
                $prod->setDsc($request->get('desc'));
                $prod->setPrice($request->get('price'));
                $prod->setStock($request->get('qty'));
                $prod->setType($request->get('type'));
                $file = $request->files->get('upload');

                if(!is_null($file)){
                    // generate a random name for the file but keep the extension
                    $filename = uniqid().".".$file->getClientOriginalExtension();
                    $path = "assets/product";
                    $file->move($path,$filename); // move the file to a path
                    $prod->setPic($filename);
                    $em->flush();
                }

                $em->persist($prod);
                $em->flush();
                return $this->redirectToRoute('company_homepage');
            }
        }
        else{
            return new Response('you are trying to access wrong route!');
        }
    }
}

但不知何故返回null代替pic的名称,因为这是我提交表单时收到的消息:

  

执行&INSTS INTO产品(名称,dsc,pic,公司,类型,价格,销售,库存)VALUES(?,?,?,?,?,?,?,?)时发生异常&#39;使用params [&#34; johnsonn的婴儿洗发水&#34;,&#34;它是一种婴儿洗发水,不会伤害眼睛,也适用于头发&#34;,null,2,&#34;婴儿用品&#34;,&#34; 150&#34;,null,&#34; 990&#34;]:

     

SQLSTATE [23000]:完整性约束违规:1048列&#39; pic&#39;不能为空

我不知道问题是什么,因为我没有在其他地方使用相同代码更新图片时出现此错误

1 个答案:

答案 0 :(得分:1)

由于代码的冗余问题,我会在您的实体中实现文件上传的逻辑。控制器应该很小,并且没有处理文件上传的逻辑。

<?php
// src/AppBundle/Bundle/Entity/Image.php

const SERVER_PATH_TO_IMAGE_FOLDER = '/server/path/to/images';

/**
 * Unmapped property to handle file uploads
 */
private $file;

/**
 * Sets file.
 *
 * @param UploadedFile $file
 */
public function setFile(UploadedFile $file = null)
{
    $this->file = $file;
}

/**
 * Get file.
 *
 * @return UploadedFile
 */
public function getFile()
{
    return $this->file;
}

/**
 * Manages the copying of the file to the relevant place on the server
 */
public function upload()
{
    // the file property can be empty if the field is not required
    if (null === $this->getFile()) {
        return;
    }

    // we use the original file name here but you should
    // sanitize it at least to avoid any security issues

    // move takes the target directory and target filename as params
    $this->getFile()->move(
        self::SERVER_PATH_TO_IMAGE_FOLDER,
        $this->getFile()->getClientOriginalName()
    );

    // set the path property to the filename where you've saved the file
    $this->filename = $this->getFile()->getClientOriginalName();

    // clean up the file property as you won't need it anymore
    $this->setFile(null);
}

/**
 * Lifecycle callback to upload the file to the server
 */
public function lifecycleFileUpload()
{
    $this->upload();
}

/**
 * Updates the hash value to force the preUpdate and postUpdate events to fire
 */
public function refreshUpdated()
{
    $this->setUpdated(new \DateTime());
}

// ... the rest of your class lives under here, including the generated fields
//     such as filename and updated

https://sonata-project.org/bundles/admin/master/doc/cookbook/recipe_file_uploads.html

然而

将此属性设置为表单标记:

enctype="multipart/form-data"

导致这个错误我建议您使用Symfony表单组件的FormTypes

http://symfony.com/doc/current/book/forms.html

为什么要在此行刷新实体管理器

$prod->setPic($filename);
$em->flush(); // <-

您是否在上传的文件中检查了move方法的return语句?