2017-02-15 9 views
0

SlimPHPを使用してファイルをダウンロードしようとしていますが、それは私のために働いていないようです。ここでSlimPHPアプリケーションがダウンロードされないファイル

は私が作ったルートです:

$backendApp->post('/export', function ($request, $response, $args) { 
     $emails = $this->orginization->exportEmails(); 
     $exportFile = $this->file->writeEmailExport($emails, 'AllEmails.csv'); 

     $fh = fopen($exportFile, "r"); 
     $stream = new \Slim\Http\Stream($fh); 

     $response = $response->withHeader('Content-Type', 'application/octet-stream') 
      ->withHeader('Content-Description', 'File Transfer') 
      ->withHeader('Content-Disposition', 'attachment; filename="' . basename($exportFile) . '"') 
      ->withHeader('Content-Length', filesize($exportFile)) 
      ->withBody($stream); 

     return $response; 
    }); 

私が知っているファイルの内容を応答に戻ってくるよう$ exportFileが有効なPHPストリーミング資源であるという事実のために、私はただトリガーに必要ユーザーのブラウザファイルのダウンロード機能

これらは、応答に存在しているのヘッダーです:

Cache-Control:no-store, no-cache, must-revalidate, post-check=0, pre-check=0 
Connection:close 
Content-Description:File Transfer 
Content-Disposition:attachment; filename="AllEmails.csv" 
Content-Length:267 
Content-Type:application/octet-stream 
Expires:Thu, 19 Nov 1981 08:52:00 GMT 
Host:localhost:8080 
Pragma:no-cache 
X-Powered-By:PHP/5.6.15 

は何でもすぐに私がここで間違ってやっていることに傑出していますか?私は、ファイルの内容を取得していることを知っているので、私はちょうどそのファイルをダウンロードするように促される必要があります。

+0

私のダウンロードファイルのコードはスリムなフレームワークを使用しておらず、私のコードは3年以上経っているので、コメントしてはいけませんが、私は疑問に思っていました - 'preg_replace("([^ \ w \ s ($ dl_file、FILTER_SANITIZE_URL) 'ここで、' '\ '\ $ dl_file'は無効な文字を削除するためのpreg_replaceの結果ですか?ファイルの内容を取得している場合は、これが助けになるとは思えません。 – Inkdot

答えて

1

それは、このコードが動作するようこれを呼び出しているしかしに近い関連:

$app = new \Slim\App($config); 

$app->get("/", function ($request, $response, $args) { 

    $response->write(
     <<<EOT 
<form method="POST" action="/export"> 
<input type="submit" value="Download"> 
</form> 
EOT 
    ); 

    return $response; 
}); 

$app->post('/export', function ($request, $response, $args) { 
    $exportFile = __DIR__ . '/../test_file.txt'; 

    $fh = fopen($exportFile, "r"); 
    $stream = new \Slim\Http\Stream($fh); 

    $response = $response->withHeader('Content-Type', 'application/octet-stream') 
     ->withHeader('Content-Description', 'File Transfer') 
     ->withHeader('Content-Disposition', 'attachment; filename="' . basename($exportFile) . '"') 
     ->withHeader('Content-Length', filesize($exportFile)) 
     ->withBody($stream); 

    return $response; 
}); 

あなたは応答]タブで情報を見ることができると言います。これはあなたがJavaScript経由でこれを引き起こしていることを意味しますか?そうであれば、ブラウザはファイルをユーザーではなくJSに送り返します。ファイルのダウンロードダイアログを表示したい場合は、ユーザーがクリックするためのボタンが付いたフォーム(POSTが必要)を入力します。

+0

ああ、ルートの呼び出しに関するあなたのコメントJavascript経由でスポットがありました。ありがとう – Xenology

関連する問題