Juice
Juice

Reputation: 3063

how to download an uploaded file in symfony1.4

I am uploading images using sfWidgetFormInputFile() to the folder MY_PROJECT/WEB/UPLOADS .How to download those files from that path. how to get the path for the uploads folder. And also when i upload a file the file name changes to somthing like this 1f3c6d9bf7b8ebda8b600576c55817c34715a8421.How can i upload with its orginal name? thanks in advance.

Upvotes: 0

Views: 2229

Answers (3)

Himanshu Bhardiya
Himanshu Bhardiya

Reputation: 1057

public function executeDownload(sfwebRequest $request)
{
    $blog_user = Doctrine_Core::getTable('login')->find($request->getParameter('id'));
    //$this->forward404Unless($res);
    //$file=$blog_user->getDoc();
    //$path=sfConfig::get('sf_upload_dir').'/'.$file;
    header('content-type:image/jpg');
    header('Content-Description: File Transfer');
    //header('Content-Type: application/octet-stream');
    header('Accept-Ranges: bytes');
    header('Content-Disposition: attachment; filename='.basename($blog_user->getDoc()));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($blog_user->getDoc()));
    ob_clean();
    flush();
    readfile($blog_user->getDoc());
    return sfView::NONE;
}

Upvotes: 0

1ed
1ed

Reputation: 3668

There is an easier way... put a generateFieldNameFilename() function into your model or form class (where FieldName is the camelized name of the field where you store the image).

// your form or model class
public function generateImageFilename(sfValidatedFile $file)
{
  return $file->getOriginalName();
}

// in your template ($model => model object)
<?php echo link_to($model->getImage(), '/uploads/'.$model->getImage(), array('target' => '_blank')); ?>
// to dispaly the image in the link
<?php echo link_to(image_tag('/uploads/'.$model->getImage()), '/uploads/'.$model->getImage(), array('target' => '_blank')); ?>

This will open your image in a new tab. If you would like to force download images in your uploads dir put a .htaccess file into it (headers module must be enabled sudo a2enmod headers):

SetEnvIf Request_URI "\.jpg$" requested_jpg=jpg
Header add Content-Disposition "attachment" env=requested_jpg

By the way symfony renames your uploaded files because filenames must be unique in a directory so if you want to keep the original name, the field where you store the filename should be unique and every model should have a separate subdirectory for its files.

Upvotes: 2

Manu
Manu

Reputation: 4500

You need to get the original filename, as such :

   $filename = $this->form->getValue('file')->getOriginalName();
   $this->exists = file_exists(sfConfig::get('sf_web_dir').$filename);

   if (!$this->exists)
     $this->form->getValue('file')->save(sfConfig::get('sf_web_dir').$filename);

Upvotes: 2

Related Questions