0

Hi I'm trying to upload a CSV file using the following form code:

$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'
)));

In my action I have:

     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.');
         }
     }

When I try to upload a CSV I always get an error, which is the mime type is incorrect

Invalid mime type (text/plain).

Any ideas why?

Thanks

terrid25
  • 1,926
  • 8
  • 46
  • 87
  • 2
    Does my post help you? http://stackoverflow.com/questions/16190929/detecting-a-mime-type-fails-in-php. Mime type detection is unreliable. – meijuh May 29 '13 at 17:37
  • 1
    You should also accept plain file (ie; mime_types `text/plain`) as csv file. What if you create a new file with your editor, save it as a csv, and want to upload it? It will have `text/plain`. It will be better to validate (using a post validator) the **content** of your csv (with `fgetcsv` etc ..), like checking if you have XX number of columns, named with this term, etc .. rather than checking the mime_types. – j0k May 30 '13 at 11:42

1 Answers1

1

I had the same problem and I solved it creating a postValidator in which I get the path of the file and I do a test to check if is a csv file or not and it works fine

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.');
            }
        }
    }
}

And you call it at the end of your form like this:

$this->mergePostValidator(new sfValidatorCSV());
Goku
  • 2,157
  • 2
  • 16
  • 31