2016-02-25 105 views
0

view.blade.php这样

.... 
<meta name="_token" content="{!! csrf_token() !!}" /> 
.... 
<script> 
jQuery(document).ready(function ($) { 
    $.ajaxSetup({ 
     headers: {'X-CSRF-Token': $('meta[name="_token"]').attr('content')} 
    }); 
    $.post('/download_file', {file_name: "abc"}, function (data) { 
     console.log(data); 
    }); 
}); 
</script> 

routes.php文件我已经设置的路线

Route::post('/download_file' , '[email protected]_file'); 

DownloadController.php我写的代码创建和下载文件中像这样

<?php 
namespace App\Http\Controllers; 

use Response; 
use File; 
use Illuminate\Http\Request; 

class DownloadController extends Controller { 

    public function load_file(Request $request){ 
     if($request->file_name === "abc"){ 
      File::put("files/abc.txt", "This is content in txt file"); 
      $file_abc = public_path() . "/files/abc.txt"; 
      return Response::download($file_abc); 
     } 
    } 

} 

文件的abc.txt是创建服务器,但之后$。员额调用浏览器不下载它。在console.log(数据)我看到文件的内容。感谢任何帮助。

回答

0

Laravel提供响应式下载开箱。官方文档陈述:

下载方法可能用于生成一个响应,强制用户的浏览器在给定的路径下载文件。下载方法接受一个文件名作为方法的第二个参数,这将决定用户下载文件时看到的文件名。最后,您可以通过HTTP头的数组作为第三个参数的方法:

return response()->download($pathToFile); 

//OR 

return response()->download($pathToFile, $name, $headers); 

所以你LOAD_FILE函数应该响应要下载的文件这样的,没有必要添加的jQuery这一点。

+0

我使用jQuery,因为我想用户开放view.blade.php后自动创建和下载文件。我改变这样的代码:$ headers = array('Content-Type:text/plain');返回响应() - >下载($ file_abc,“abc.txt”,$ headers);'但它不起作用。 –

+0

使文件下载只需HREF用户指向LOAD_FILE功能的路线和您的下载应该开始 – rohitarora