图像文件不想下载Laravel

时间:2019-02-27 23:18:54

标签: laravel

Output当我运行代码时,我要从我的文件夹下载的图像出现在XHR-> Chrome中预览,但不想开始下载。我根据Laravel文档使用代码:

$file = public_path()."/files/projects/".$name;
$headers = array('Content-Type: image/jpeg');
return response()->download($file,$name,$headers);

我看不出有什么问题。这与我见过的许多代码非常相似。

1 个答案:

答案 0 :(得分:0)

我们使用标头,并且拥有Laravel 5.1,但在短时间内缓存文件并使用c3插件创建图的动态图像时,我们做了一些不同的操作。在我的文章的结尾,我将展示如何使用带缓存的标头。

确保添加路线:

Route::get('/files/projects/{file}', 'DownloadController@index');

See this SO post

$file= public_path(). $name;

Laravel <5

$headers = array(
          'Content-Type: image/jpeg',
        );

  return Response::download($file, $name.'jpg', $headers);

Laravel> = 5

  return response()->download($file, $name."jpg");

注意:这是一个缓存的图片实现...(请注意二进制文件的base64_encode,即:.png .jpg)

  $responseHeaders = array(
            'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0',
            'Content-Type' => 'image/png',
            'Content-Disposition' => 'attachment; filename=' . $outputFileName . '.png',
            'Expires' => '0',
            'Pragma' => 'public'
        );


$url = action('DownloadController@standAlone', ['cat' => $category]);

        // Values cached for 1 minute... ???
        if (Cache::has($url)){
            return Response(base64_decode(Cache::get($url)))->withHeaders($responseHeaders);
        } else {
            $maxWidth = 2560;
            $maxHeight = 854;
            $minWidth = 780;
            $minHeight = 260;

            if ($height > $maxHeight) {
                $height = $maxHeight;
            }

            if ($height < $minHeight) {
                $height = $minHeight;
            }

            if ($width > $maxWidth) {
                $width = $maxWidth;
            }

            if ($width < $minWidth) {
                $width = $minWidth;
            }

            $command = app_path('bin/phantomjs');
            $command .= ' ' . app_path('bin/maketrendpng.js');
            $command .= ' ' . escapeshellarg($url);
            $command .= ' /dev/stdout';
            $command .= ' ' . escapeshellarg($height);
            $command .= ' ' . escapeshellarg($width);
            $command .= ' ' . request()->server->get('SERVER_NAME');
            $command .= ' ' . escapeshellarg($_COOKIE[env('SESSION_COOKIE', 'laravel_session')]);
            $command .= ' ' . escapeshellarg(env('SESSION_COOKIE', 'laravel_session'));

            $handle = popen($command, 'r');

            $contents = '';

            while (!feof($handle)) {
                $contents .= fread($handle, 8192);
            }

            pclose($handle);

    Cache::put($url, base64_encode($contents), 1);

    return Response($contents)->withHeaders($responseHeaders);