Created
September 17, 2014 14:07
-
-
Save markhowellsmead/6779f86d87d69f459f64 to your computer and use it in GitHub Desktop.
TYPO3 ExtBase: Force download of a file from a controller action. Example will force download a file from a folder defined in the TypoScript settings for the extension
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param string $fileName | |
* @return void | |
*/ | |
public function downloadAction($fileName) { | |
$file = $this->settings['uploadFolder'] . 'uploadedPhotos/' . $fileName; | |
if(is_file($file)) { | |
$fileLen = filesize($file); | |
$ext = strtolower(substr(strrchr($fileName, '.'), 1)); | |
switch($ext) { | |
case 'txt': | |
$cType = 'text/plain'; | |
break; | |
case 'pdf': | |
$cType = 'application/pdf'; | |
break; | |
case 'exe': | |
$cType = 'application/octet-stream'; | |
break; | |
case 'zip': | |
$cType = 'application/zip'; | |
break; | |
case 'doc': | |
$cType = 'application/msword'; | |
break; | |
case 'xls': | |
$cType = 'application/vnd.ms-excel'; | |
break; | |
case 'ppt': | |
$cType = 'application/vnd.ms-powerpoint'; | |
break; | |
case 'gif': | |
$cType = 'image/gif'; | |
break; | |
case 'png': | |
$cType = 'image/png'; | |
break; | |
case 'jpeg': | |
case 'jpg': | |
$cType = 'image/jpg'; | |
break; | |
case 'mp3': | |
$cType = 'audio/mpeg'; | |
break; | |
case 'wav': | |
$cType = 'audio/x-wav'; | |
break; | |
case 'mpeg': | |
case 'mpg': | |
case 'mpe': | |
$cType = 'video/mpeg'; | |
break; | |
case 'mov': | |
$cType = 'video/quicktime'; | |
break; | |
case 'avi': | |
$cType = 'video/x-msvideo'; | |
break; | |
//forbidden filetypes | |
case 'inc': | |
case 'conf': | |
case 'sql': | |
case 'cgi': | |
case 'htaccess': | |
case 'php': | |
case 'php3': | |
case 'php4': | |
case 'php5': | |
exit; | |
default: | |
$cType = 'application/force-download'; | |
break; | |
} | |
$headers = array( | |
'Pragma' => 'public', | |
'Expires' => 0, | |
'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0', | |
'Cache-Control' => 'public', | |
'Content-Description' => 'File Transfer', | |
'Content-Type' => $cType, | |
'Content-Disposition' => 'attachment; filename="'. $fileName .'"', | |
'Content-Transfer-Encoding' => 'binary', | |
'Content-Length' => $fileLen | |
); | |
foreach($headers as $header => $data) | |
$this->response->setHeader($header, $data); | |
$this->response->sendHeaders(); | |
@readfile($file); | |
} | |
exit; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment