2012-08-12 27 views
0

我正在尝试做的事我从未做过。我使用CakePHP构建表单,我使用表单助手来完成此操作。这一切都适用于输入和textareas,但我现在试图将我的两个输入更改为文件上传字段。使用CakePHP上传文件(PDF和图像)

这个我已经做了,似乎是工作,当我调试$ this-> data ['Event'] ['img'](窗体是调用事件)。我得到以下输出:

Array 
(
    [name] => logo.gif 
    [type] => image/gif 
    [tmp_name] => /tmp/phpaU3aBa 
    [error] => 0 
    [size] => 7318 
) 

现在我在这里客串,但我将不得不将文件保存到我的“根目录”文件夹。我已经创建了路径/ webroot/eventfiles/img & webroot/eventfiles/pdf - 我已经开始只是为了现在做图像,所以我可以让它工作,但我将上传的其他文件类型是pdf。

现在我已经看了一下CakePHP的网站,但我只是说看看PHP网站,似乎有很多方法来做到这一点,但我不知道如何保存它。以便我稍后可以访问它,例如它会进入webroot文件夹,以便Cake可以看到它。

另外,作为一个附注,还需要将路径+文件名保存到数据库中。这,除非我错了,应该很容易,只需使用$ this-> data ['Event'] ['img'] ['name']并将其保存到我的数据库中。

请帮忙?我一直在为此工作好几天。我似乎无法绕过文件上传。有没有简单的方法来做到这一点?例如蛋糕如何HTML &表单助手,一种简单的方法来保存上传的文件?

感谢您的任何帮助,您可以给。

Glenn。

+0

我知道很多人说你应该在发帖之前搜索这个网站,在我的辩护中我这样做了,有很多关于文件上传的帖子和我尝试过的帖子都没有用!但是,这一个,http://stackoverflow.com/questions/2872364/how-to-save-image-in-cakephp?rq=1 - 有一点编辑! – 2012-08-12 18:55:12

回答

0

虽然我会发布我的答案,这完全有效。我从两个文件输入文件获取pdf和jpeg图像,然后重命名为给定标题,由用户在输入文本字段中提供。使用$ newevent中的两个变量,这些变量与其他输入一起被保存到数据库,路径和重命名的图像中。

此代码非常简单。这段代码的主体来自这个网站上的一篇文章,我刚刚改变它用于我的使用。

如果您还尝试添加/上传不同的文件类型,例如doc或者png,所有你需要知道的是你想要上传的文档的头文件类型并将其添加到if语句中。

希望这会帮助别人!

Glenn。

  $pathimg = "/eventfiles/img/"; 
      $pathpdf = "/eventfiles/pdf/"; 
      $dir_pdf = getcwd().$pathpdf; 
      $dir_img = getcwd().$pathimg; 
      $PDF_Path = $dir_pdf . $this->data['Event']['pdf']["name"]; 
      $IMG_Path = $dir_img . $this->data['Event']['img']["name"]; 
      $IMG_WithOutSpace = preg_replace('/\s+/', '_', $newevent['title']); 
      $PDF_WithOutSpace = preg_replace('/\s+/', '_', $newevent['title']); 

      $newevent['img'] = "/vh/eventfiles/img/" . $IMG_WithOutSpace . ".jpg"; 
      $newevent['pdf'] = "/vh/eventfiles/pdf/" . $PDF_WithOutSpace . ".pdf"; 

     if ((($this->data['Event']['img']["type"] == "application/pdf") || ($this->data['Event']['img']["type"] == "image/jpeg"))) { 
      if (($this->data['Event']['img']["error"] > 0) || ($this->data['Event']['pdf']["error"] > 0)) { 
      $this->Session->setFlash(__('An error has occured during updating. Please check all the fields.', true), 'default', array('class' => 'error-message')); 
      $this->redirect($this->referer()); 
      exit(); 
      } else { 

       move_uploaded_file($this->data['Event']['img']["tmp_name"], $IMG_Path); 
       rename($IMG_Path, $dir_img . $IMG_WithOutSpace. ".jpg"); 

       move_uploaded_file($this->data['Event']['pdf']["tmp_name"], $PDF_Path); 
       rename($PDF_Path, $dir_pdf . $PDF_WithOutSpace . ".pdf"); 

       $filename= $this->data['Event']['pdf']["name"]; 
       $filename= $this->data['Event']['img']["name"]; 
      } 
+0

请注意,这是为了在CakePHP中工作而构建的,因此可能有些功能在没有Cake框架的情况下可能无法在PHP中运行。 – 2012-08-13 07:57:38