如何使用AngularJS和ui-router从Laravel 5.1获取下载文件

How to get download file from Laravel 5.1 with AngularJS and ui-router

本文关键字:获取 下载 文件 Laravel 何使用 AngularJS ui-router      更新时间:2023-09-26

我在 laravel 中有这段代码用于导出 excel:

public function export_excel(Request $request){      
    $user = user::all();
    Excel::create('user', function($excel) use($user) {
        $excel->sheet('Sheet 1', function($sheet) use($user) {
            $sheet->fromArray($user);
        });
    })->download('xls');
}

我的路线是:

Route::get('user/export/excel','UserController@export_excel');

我的 html 是:

<a><i class="fa fa-file-excel-o"></i> Export to Excel</a>

我想使用 Restangular 从 REST API 发送请求,然后获取下载文件。

我解决了这个问题:

this.downloadExcel = function(){
        Restangular.one('user/export/excel').withHttpConfig({responseType: 'blob'}).get().then(function(response) {
             var url = (window.URL || window.webkitURL).createObjectURL(response);
             window.open(url,"_self");
        })
    }

你可以简单地使用 href 属性

<a href="user/export/excel" target="_BLANK">
   <i class="fa fa-file-excel-o"></i> Export to Excel
</a>