这是一行让我恶心的代码。
return Response::download(storage_path().'/file/' . $file->id . "." . $file->file->extension);
文件被上传,并被赋予一个id,保存在例如25.pdf
下。如果文件是PDF,但不适用于其他任何内容,例如PNG,这很好。我们从Laravel 3升级到4,试图克服这个问题。
有什么想法吗?
编辑:我刚刚上传了一个测试文本文件,里面有单词test。我上传了它,然后下载了它。我打开它,有3行空白和字母te!!!!!我通过sftp下载了它,文件正确地存储在服务器上,所以这是一个挑衅的下载过程!
我使用了这个函数,而不是Laravel的任何东西。:/(从网上其他地方偷来的)
public static function big_download($path, $name = null, array $headers = array()) {
if (is_null($name))
$name = basename($path);
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$pathParts = pathinfo($path);
// Prepare the headers
$headers = array_merge(array(
'Content-Description' => 'File Transfer',
'Content-Type' => finfo_file($finfo, $path),
'Content-Transfer-Encoding' => 'binary',
'Expires' => 0,
'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0',
'Pragma' => 'public',
'Content-Length' => File::size($path),
'Content-Disposition' => 'inline; filename="' . $name . '.' . $pathParts['extension'] . '"'
), $headers);
finfo_close($finfo);
$response = new Symfony'Component'HttpFoundation'Response('', 200, $headers);
// If there's a session we should save it now
if (Config::get('session.driver') !== '') {
Session::save();
}
// Below is from http://uk1.php.net/manual/en/function.fpassthru.php comments
session_write_close();
ob_end_clean();
$response->sendHeaders();
if ($file = fopen($path, 'rb')) {
while (!feof($file) and (connection_status() == 0)) {
print(fread($file, 1024 * 8));
flush();
}
fclose($file);
}
// Finish off, like Laravel would
Event::fire('laravel.done', array($response));
$response->foundation->finish();
exit;
}
有人可能会问,我如何获取laravel中文件的路径?
文件路径可以实现如下:
public function getDownload(){
$file = public_path()."/downloads/info.pdf";
$headers = array('Content-Type: application/pdf',);
return Response::download($file, 'info.pdf',$headers);
}
函数将从"project/public/download"文件夹下载文件。
(别忘了自己设置路线和控制器)
尝试在返回中包含MIME:
$file = storage_path().'/file/' . $file->id . "." . $file->file->extension;
return Response::download($file, 200, array('content-type' => 'image/png'));
如果您使用的是Windows,请转到php.ini,然后取消注释"extension=php_fileinfo.dll"部分,然后使用以下代码:
Route::get('file/download', function()
{
$file = public_path(). ''download'myfile.png';
return Response::download($file);
});