2013-05-29 71 views
0

嗨,我尝试使用以下格式的代码上传CSV文件:CSV上传 - MIME类型

$this->widgetSchema ['file'] = new sfWidgetFormInputFile(); 

$this->setValidator('file', new sfValidatorFile(array(
      'required'  => true, 
      'path'   => sfConfig::get('sf_upload_dir') . '/properties/csv', 
      'mime_categories' => array('csv' => array('text/csv', 'application/csv', 'application/excel', 'application/vnd.ms-excel', 'application/vnd.msexcel')), 
      'mime_types'  => 'csv' 
))); 

在我的行动,我有:

 if($request->isMethod('post')) 
    { 
     $propertyCsvForm->bind($request->getParameter($propertyCsvForm->getName()), $request->getFiles($propertyCsvForm->getName())); 
     if($propertyCsvForm->isValid()) 
     { 
      $this->getUser()->setFlash('success-csv', 'The CSV was successfully imported.'); 
     } else { 
      $this->getUser()->setFlash('error-csv', 'The CSV could not be imported.'); 
     } 
    } 

当我尝试上载CSV我总是得到一个错误,这是MIME类型是不正确

Invalid mime type (text/plain).

任何想法为什么?

感谢

+2

我的帖子可以帮你? http://stackoverflow.com/questions/16190929/detecting-a-mime-type-fails-in-php。 Mime类型检测不可靠。 – meijuh

+1

您还应该接受普通文件(即; mime_types'text/plain')作为csv文件。如果你用你的编辑器创建一个新文件,将它保存为csv,并想上传它?它将具有“文本/纯文本”。验证(使用post验证器)你的csv的**内容**(用'fgetcsv'等..)将会更好,比如检查你是否有XX列数,用这个术语命名等。比检查mime_types。 – j0k

回答

1

我有同样的问题,我解决它创建一个postValidator中,我得到的文件的路径和我做一个测试,以检查是否是一个CSV文件或不和它工作正常

class sfValidatorCSV extends sfValidatorSchema 
{ 
    protected function configure($options = array(), $messages = array()) 
    { 
     parent::configure($options, $messages); 
    } 

    protected function doClean($values) 
    { 
     $file = $values['file']; 

     if(empty($file)==false) 
     { 
      $filename = $file->getOriginalName(); 

      $path = pathinfo($filename); 

      if($path['extension']!="csv") 
      { 
       throw new sfValidatorError($this, 'Invalid extension.'); 
      } 
     } 
    } 
} 

而你把它在你的表格是这样结尾:

$this->mergePostValidator(new sfValidatorCSV()); 
+1

如果csv文件实际上是一个zip文件会怎么样? Boum :) – j0k

+0

该文件将永远是一个CSV – terrid25

+0

所以删除''mime_types'=>'csv'' – DOZ