terrid25
terrid25

Reputation: 1946

CSV Upload - mime types

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

Upvotes: 0

Views: 1908

Answers (1)

Goku
Goku

Reputation: 2139

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());

Upvotes: 1

Related Questions