从存储中下载文件不起作用?

时间:2016-10-17 12:53:37

标签: php laravel

实际上我的任务是当我使用日期选择器从日期和日期中选择然后我点击下载按钮,从日期之间的订单表中选择ID并检查发票 - > id与存储文件夹中的文件匹配。如果匹配文件,请创建zip并下载。

我可以压缩但下载无效。

Click Here for firebug console result

export.blade.php

<button class="btn btn-success dateDifference" role="button"><i class="fa fa-download"></i> Download </button>

<script>
        $(".dateDifference").on("click", function() {
        var fromDate = $(".dateFrom").val();
        var toDate   = $(".dateTo").val();
        $.post('{{ route('exportInvoiceDownload') }}', {fromDate: fromDate, toDate: toDate}, function(response){
            //alert(response);
        });
    });
</script> 

routes.php文件

Route::post('/export/download/invoices',  [
        'as' => 'exportInvoiceDownload', 'uses' => 'BookingController@downloadInvoices'
    ]);

Controller.php这样

public function downloadInvoices(Request $request)
    {
        $fromDateReplace     = str_replace('/', '-', $request->fromDate);
        $fromDate            = date("Y-m-d", strtotime($fromDateReplace));
        $toDateReplace       = str_replace('/', '-', $request->toDate);
        $toDate              = date("Y-m-d", strtotime($toDateReplace));
        $archive_name = storage_path('app') . '/invoice_archive/Rechnung_'.$fromDate.'_'.$toDate.'.zip';
        $orders = Booking::select('invoice_id')
            ->whereBetween('created_at', [$fromDate, $toDate])
            ->get();
        if (count($orders) > 0 ) {
            $zip = new ZipArchive;
            if ($zip->open($archive_name, ZipArchive::CREATE) === TRUE) {

                foreach ($orders as $order) {
                    $file = storage_path('app') . '/invoice_archive/test-'.$order->invoice_id.'.pdf';
                    if (file_exists($file)) {
                        $zip->addFile($file, 'test-'.$order->invoice_id.'.pdf');
                    }
                }
                $zip->close();
                $headers = [
                    'Pragma'                    => 'public',
                    'Expires'                   => 0,
                    'Content-Type'              => 'application/octet-stream',
                    'Content-Disposition'       => 'attachment; filename=\"test_'.$fromDate.'_'.$toDate.'.zip\"',
                    'Content-Transfer-Encoding' => 'binary'
                ];
                if (file_exists($archive_name)) {
                    return response()->download($archive_name, 'test_'.$fromDate.'_'.$toDate.'.zip', $headers) /*->deleteFileAfterSend(TRUE)*/;
                }
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

似乎你用ajax调用这条路由,如果真的比下载在这种情况下不起作用,你需要传统的post请求,因为ajax二进制响应不会打开下载弹出窗口浏览器所以不是ajax只是将表单作为浏览器默认提交或者让它获取请求并在新的浏览器选项卡中打开它然后它会考虑内容 - 处置标题和下载弹出窗口。