简体   繁体   中英

How to pass long filename in url and download the file using php function?

I have a following function that downloads the file whose name is passed as a parameter in the url. Here is the code:

    public function actionDownloadFile($filename)
    {
        $file = Yii::app()->request->getBaseUrl(true) . '/upload/digitaluploads/' . $filename; 
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . basename($file) . '"');
        readfile($file);
    }

This function is called from view file when the user clicks on download button from the view:

<a class="digital-download" href="<?php echo Yii::app()->request->getBaseUrl('true'); ?>/site/downloadfile/filename/<?php echo urlencode($digital_download['filename']); ?>">Click here to download</a>

This works for filename that don't have spaces like it will work for file with the name like somefile.mp3 but it does not work for the files that have spaces in that. ie it fails for the files whose name contains spaces like 'maid with the flaxen hair.mp3' .

As you can see I have even encoded the parameter in the url using urlencode. I tried using decode in action as well but all I get is the broken page.

Anyone?

尝试这个 :

str_replace(' ', '%20', 'your url here');

use this function to avoid space and other possible problems:

function fullescape($in) 
{ 
  $out = ''; 
  for ($i=0;$i<strlen($in);$i++) 
  { 
    $hex = dechex(ord($in[$i])); 
    if ($hex=='') 
       $out = $out.urlencode($in[$i]); 
    else 
       $out = $out .'%'.((strlen($hex)==1) ? ('0'.strtoupper($hex)):(strtoupper($hex))); 
  } 
  $out = str_replace('+','%20',$out); 
  $out = str_replace('_','%5F',$out); 
  $out = str_replace('.','%2E',$out); 
  $out = str_replace('-','%2D',$out); 
  return $out; 
} 

found here: http://php.net/manual/en/function.urlencode.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM