Skip to content

Instantly share code, notes, and snippets.

@dkesberg
Created February 24, 2014 12:00
Show Gist options
  • Select an option

  • Save dkesberg/9187121 to your computer and use it in GitHub Desktop.

Select an option

Save dkesberg/9187121 to your computer and use it in GitHub Desktop.
Laravel workaround for Symphony Download Response Error: "the filename fallback must only contain ASCII characters". Creates a tempfile for download. Also registers a shutdown function to clean tmp dir.
<?php
// Add include to app/start/global.php
/*
|--------------------------------------------------------------------------
| Shutdown cleanup
|--------------------------------------------------------------------------
|
| Remove tmp files
*/
require app_path().'/shutdown.php';
<?php
/**
* @author Daniel Kesberg <[email protected]>
* @copyright (c) 2014, Daniel Kesberg
*/
class ItemController extends BaseController
{
public function download(Item $item)
{
// there is a problem with tempnam, copy und filesize:
// if you use copy(), the filesize() function used by Response::download
// always returns 0 and you download an empty file
// version 1:
// create tmpfile with tempnam and use stream_copy_to_stream
$tmpFilename = tempnam(realpath(app_path() . '/../tmp'), 'download');
$downloadStream = fopen($item->filepath, 'r');
$tmpStream = fopen($tmpFilename, 'w');
stream_copy_to_stream($downloadStream, $tmpStream);
// version 2:
// create tmpfile and add a random string to the generated filename
$tmpFilename = tempnam(realpath(app_path() . '/../tmp'), 'download');
$tmpFilename .= uniqid();
copy($entry->pathSrc(), tmpFilename);
// build the response
// use Str::ascii on the original Filename
// detect mime type
return Response::download($tmpFilename, Str::ascii($item->filename), array(
'Content-Type'=> mime_content_type($item->filepath)
));
}
}
<?php
/**
* @author Daniel Kesberg <[email protected]>
* @copyright (c) 2014, Daniel Kesberg
*/
function cleanup_tmp()
{
$path = realpath(app_path() . '/../tmp');
$files = glob($path . '/download*');
foreach($files as $file) {
unlink($file);
}
}
register_shutdown_function('cleanup_tmp');
@hayleyxyz
Copy link

Hit this problem too...

Came up with this workaround: https://gist.github.com/kimoi/9465a20c4e09d03c122a

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment