15

Codeigniter のドキュメントを読んで、次のコードを使用して、サーバーからファイルを強制的にダウンロードしています。

function download($file_id){
        $file = $this->uploadmodel->getById($file_id); //getting all the file details
                                                      //for $file_id (all details are stored in DB)
        $data = file_get_contents($file->full_path); // Read the file's contents
        $name = $file->file_name;;

        force_download($name, $data);
    }

コードは画像の作業ファイルですが、PDF ファイルの場合は動作しません。すべてのファイル拡張子でテストしたわけではありませんが、PDF では機能しないため、他のさまざまなファイル タイプでは機能しない可能性があります。解決策はありますか?

4

3 に答える 3

23

同様の問題がありました。問題は、ブラウザに送信される特定の MIME とヘッダーにあると思います。ここで見つけたコードを使用することになりましたhttp://taggedzi.com/articles/display/forcing-downloads-through-codeigniter。force_download の代わりに以下の関数を使用してください。これまでのところうまくいきました。

    function _push_file($path, $name)
    {
      // make sure it's a file before doing anything!
      if(is_file($path))
      {
        // required for IE
        if(ini_get('zlib.output_compression')) { ini_set('zlib.output_compression', 'Off'); }

        // get the file mime type using the file extension
        $this->load->helper('file');

        $mime = get_mime_by_extension($path);

        // Build the headers to push out the file properly.
        header('Pragma: public');     // required
        header('Expires: 0');         // no cache
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Last-Modified: '.gmdate ('D, d M Y H:i:s', filemtime ($path)).' GMT');
        header('Cache-Control: private',false);
        header('Content-Type: '.$mime);  // Add the mime type from Code igniter.
        header('Content-Disposition: attachment; filename="'.basename($name).'"');  // Add the file name
        header('Content-Transfer-Encoding: binary');
        header('Content-Length: '.filesize($path)); // provide file size
        header('Connection: close');
        readfile($path); // push it out
        exit();
    }
}

それが役に立てば幸い。

于 2013-02-12T18:22:04.503 に答える
10

.pdfsでも機能しています。ファイルへのパスを確認してください - それが問題かもしれません。
私もその問題を抱えていましたが、ファイルへのパスを修正すると、完全に機能しました。
以下は私がコードを書いた方法です:

if($src ==  "xyyx")
{
$pth    =   file_get_contents(base_url()."path/to/the/file.pdf");
$nme    =   "sample_file.pdf";
force_download($nme, $pth);     
}
于 2013-10-29T12:06:06.653 に答える