0

我正在尝试将文件上传到 webroot/files 目录。我还在我的数据库表中包含了该文件的记录。

将文件保存到数据库有效,我使用 move_uploaded_file() 方法,但它不起作用。它不会返回任何错误,但文件不会显示在文件夹中。我检查了权限,它们都是 755。这是我控制器中的操作:

if ($this->request->is('post'))
  {
      $uploadedFile = array();
      $filename = $this->request->data['Document']['MyFile']['name'];
      $fileData = fread(fopen($this->request->data['Document']['MyFile']['tmp_name'], "r"), $this->request->data['Document']['MyFile']['size']);

      $uploadedFile['MyFile']['name'] = $this->request->data['Document']['MyFile']['name'];
      $uploadedFile['MyFile']['type'] = $this->request->data['Document']['MyFile']['type'];
      $uploadedFile['MyFile']['size'] = $this->request->data['Document']['MyFile']['size'];
      $uploadedFile['MyFile']['data'] = $fileData;

  $filePath = WEBROOT_DIR . DS . 'files' . DS . $uploadedFile['MyFile']['name'];
 debug($filePath);
      if (move_uploaded_file($filename, $filePath))
      {
          echo "No Error";
          $this->Session->setFlash('Uploaded file has been moved SUCCESS.');
      }
      else
      {
          $this->Session->setFlash('Unable to Move file.');
      }
      if ($this->MyFile->save($uploadedFile))
      {
          $this->Session->setFlash('Uploaded file has been saved.');
      }
      else
      {
          $this->Session->setFlash('Unable to save file.');
      }
  }

这是来自debug($filePath); 'webroot/files/filename' -> 的输出,其中 filename 是上传文件的实际名称。

任何帮助都会很棒。谢谢

更新------------------------------------------------ 我调试了 $this->request->data,这是我上传小文件时的输出。

array(
    'Document' => array(
        'MyFile' => array(
            'name' => 'add.ctp',
            'type' => 'application/octet-stream',
            'tmp_name' => '/tmp/phpcxBA9B',
            'error' => (int) 0,
            'size' => (int) 3700
        )
    )
)

我还在下面添加了一条 else 语句move_uploaded_file(),它确实将闪存设置为无法移动文件。

我仍然不确定为什么,它可以是$filename$filePath变量吗?

谢谢

4

3 回答 3

1

您是否尝试过使用常量WWW_ROOT而不是WEBROOT_DIR?您需要提供文件系统的路径。

于 2012-08-06T19:51:20.897 回答
1

你需要移动'tmp_name',即

$filename = $this->request->data['Document']['MyFile']['tmp_name'];
于 2012-08-10T12:13:11.047 回答
1

您可能会遇到以下问题:

$filePath = WEBROOT_DIR . DS . 'files' . DS . $uploadedFile['MyFile']['name'];

错误消息将如下所示:

move_uploaded_file(webroot\files\File_Name): failed to open stream: No such file or directory [APP\Controller\CustomerController.php cakephp

如果是这样,请将上面的行替换为:

$filePath = WWW_ROOT . DS . 'files' . DS . $uploadedFile['MyFile']['name'];

方法,

WEBROOT_DIR . DS . 

WWW_ROOT .

它会移动上传的文件。

于 2013-09-19T18:47:11.513 回答