【问题标题】:Problems uploading one file in Symfony 2在 Symfony 2 中上传一个文件时出现问题
【发布时间】:2018-01-07 06:28:45
【问题描述】:

我的应用中有这个表单,我想添加一个上传文件字段。我一直在阅读文档,当我测试它时,它不会上传文件。什么都没有发生。

这是实体

 /**
 * @var string
 *
 * @ORM\Column(name="mynewpdf", type="string", length=350, nullable=true)
 */
private $mynewpdf;


/**
 * Set mynewpdf
 *
 * @param string $mynewpdf
 * @return userinfoid
 */
 public function getmynewpdf()
{
    return $this->mynewpdf;
}


/**
 * Get mynewpdf
 *
 * @return string 
 */
public function setmynewpdf($mynewpdf)
{
    $this->mynewpdf = $mynewpdf;

    return $this;
}



 public function getPath()
{
    $path = __DIR__.'/../../../../web/newfolder/';
    $path .= '/'.$this->mynewpdf;

    return $path;
} public function uploadmynewpdf($destinationDirectory)
{
    if (null === $this->mynewpdf) return;

    $nameFilePdf = uniqid().'.'.$this->mynewpdf->getClientOriginalExtension();
    $this->_createdirectory($destinationDirectory);
    $this->mynewpdf->move($destinationDirectory, $nameFilePdf);
    $this->setmynewpdf($nameFilePdf);
}

 private function _createdirectory($destinationDirectory)
{
   $path = __DIR__.'/../../../../web/newfolder/';  
   if (!file_exists($path)) @mkdir($path, 0777, true);
   $this->_createFileIndex($path);

   if (!file_exists($destinationDirectory)) @mkdir($destinationDirectory, 0777, true);
   $this->_createFileIndex($destinationDirectory);       
}

 private function _createFileIndex($myfolder)
{
   $newfile = $myfolder.'index.html';
   $content = "<html><head><title>403 Forbidden</title></head>".
                "<body>This is Forbidden</body></html>";


   if (!file_exists($newfile))
   {
      if (!$handle = @fopen($newfile, 'c')) die("Could not open/create new file");
      if (@fwrite($handle, $content) === FALSE) die("Could not write the new file");            
      @fclose($handle);
   }
   return true;
}

我的控制器:

   $file = $userinfoid->getMynewpdf();

    if($file != null)
    {
    $fileName = md5(uniqid()).'.'.$file->guessExtension();
    $file->move(
            $this->container->getParameter('pdf_directory'),
            $fileName
        );
    $userinfoid->setMynewpdf($fileName);}

最后是表格:

<form action="{{ path('add_document') }}" method="post"  >

<input type="hidden" name="data[userinfoid]" value="{{ data.userinfoid }}" />

<div class="span12">
            <label>Information about file</label> 
            <p>            
             <textarea id="fileinformation" rows="3" class="span11 campoInvalido" maxlength=""
                       title="Add some information"
                       name="data[fileinformation]" ></textarea>   
            </p>        
          </div>     

    <input type="file" id="mynewpdf" name="data[mynewpdf]" accept="application/pdf

    </form>

我不认为该表格是按应有的方式制作的。但现在我无法改变它。有人可以告诉我如何使这项工作吗?

更新:

首先,不要忘记分享有关代码问题的关键细节。

这是一个 Ajax 表单。我从没提过,应该提过。

我的 ajax 请求是这样的:

$.ajax({
       type:'POST',
       url:'page/upload',
       data: $("form").serialize(),
       beforeSend:function(){$("#loadingModal").show();},        
       dataType:'json'})

上面的代码不处理文件上传,因为它序列化了数据。所以我用这个替换了代码:

var formData = new FormData($("form")[0]);
    $.ajax({
       type:'POST',
       url:'page/upload',
       data: formData,
       cache: false,
       contentType: false,
       processData: false,
       beforeSend:function(){$("#loadingModal").show();},        
       dataType:'json'})

然后在我的控制器中,我使用了以下代码:

$request = $this->getRequest();
           $file = $request->files->get('mynewpdf');

   // If a file was uploaded
   if(!is_null($file)){
      // generate a random name for the file but keep the extension

       $filename = uniqid().".".$file->getClientOriginalExtension();

       $userinfoid->setMynewpdf($filename);
      $file->move(
                $this->container->getParameter('pdf_directory'),
                $filename
            ); // move the file to a path

   }

现在我可以在我的 Web 应用程序中保存文件了!

感谢 Gabriel Diez 的帮助!

【问题讨论】:

    标签: php file symfony upload


    【解决方案1】:

    我认为主要问题是您的表格。在你上传文件并将它发送到你的动作控制器的那一刻,什么都没有传递,因为你的输入类型文件不像 symfony 想要的那样。 你应该看一下关于如何正确上传文件的 symfony 文档,它非常清晰和完整,我认为你错过了一些重要的细节。

    https://symfony.com/doc/2.8/controller/upload_file.html

    而且为了生成表单,你应该使用 symfony 的表单助手,这是正确和安全地完成它的最好和最快的方法。

    https://symfony.com/doc/2.8/forms.html

    如果您仔细查看文档,您可以在动作控制器中看到:

    $product = new Product();
    $form = $this->createForm(ProductType::class, $product);
    

    在您的情况下,产品将是您的实体。

    然后将 $form 传递给视图。

    在 createForm 方法中,您传递了表单的实体,因此 symfony 知道表单中传递的实体类型。因此,当它构建表单并提交表单时,它会将输入文件与您的属性 $mynewpdf 相关联,因此当您调用时:

    $userinfoid->getMynewpdf();
    

    您的文件将出现,然后您可以对其进行操作。

    祝你好运

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-28
      • 1970-01-01
      • 1970-01-01
      • 2018-02-01
      • 2021-09-03
      • 2013-10-13
      • 1970-01-01
      相关资源
      最近更新 更多