php - 从 Laravel 返回的用于下载 Excel 文件的数据是无稽之谈,如何解决?
问题描述
我有一个项目,我在刀片文件中使用 vue.js,为了导出 excel,我正在尝试这种方法,它给出了这样的响应:
这是代码结构:
在 Blade.php 中(有一个按钮,它正在获取 startDate、endData 以获取 Result :
<button v-if="db_query!=null" @click="save_excel()" id="send" type="button" class="btn btn-success">Export</button>
save_excel:function(){
let self=this;
let start_at=$('#start_at').val();
let end_at=$('#end_at').val();
$.ajax({
type: "post",
url: "{{route('report.save_as_excel')}}",
data: {
_token:"{{csrf_token()}}",
name :self.name,
created_at :self.created_at,
file_id :self.file_id,
order :self.order,
paid_price :self.paid_price,
phone :self.phone,
price :self.price,
products :self.products,
products_desc :self.products_desc,
products_order_desc :self.products_order_desc,
reagents :self.reagents,
status :self.status,
time_id :self.time_id,
unpaid_price :self.unpaid_price,
check_box :self.check_box,
'end_at' :end_at,
'start_at' :start_at,
},
success: function (response) {
self.result=response.customers;
console.log(response);
window.open(response);
}
});
},
CustomerAtlasExports.php
class CustomerAtlasExports implements FromQuery, Responsable
{
use Exportable;
public $start;
public $end;
public $where;
private $fileName = 'Gozaresh.xlsx';
public function __construct($start,$end,$where)
{
$this->start = $start;
$this->end = $end;
$this->where = $where;
}
public function query()
{
return Customer::with(['products','reagents'])->whereBetween('created_at',[$this->start,$this->end])->where($this->where)->get();;
}
}
控制器.php:
$where=$this->c_query_builder();
$start=Carbon::createFromTimestamp(substr($request->start_at,0,10))->hour(0)->minute(0)->second(0);
$end=Carbon::createFromTimestamp(substr($request->end_at,0,10))->hour(23)->minute(59)->second(59);
return (new CustomerAtlasExports($start,$end,$where));
在他们解释的文档中,我应该获取文件来下载它,我还尝试->Download
在控制器中使用而不是在导出文件中使用 Responsable。
解决方案
您不能通过 AJAX 下载文件。数据最终出现在网页中的 JavaScript 变量中,而不是磁盘上的文件。(好吧,有时有一种方法可以用一些 JavaScript 来伪造它,但不建议这样做,并且可能并不总是有效)。
如果您想通过 JavaScript 启动下载,通常的方法是使用 window.open() 或 window.location 直接在浏览器中打开一个新 URL,这会导致下载发生。然后它通过常规请求而不是 ajax 完成,并以您期望的方式处理。
在您的情况下,如果您要发布要转换为 Excel 文件的数据,我会让 PHP 返回一个 URL 作为对 AJAX 请求的响应。该 URL 将指向 Excel 文件在服务器上的保存位置。然后在 AJAX 请求代码的“成功”回调中,使用 JavaScript(如上所述)告诉浏览器访问该 URL。
NB 您可能还需要考虑在服务器上使用 cron 作业或其他东西来在一段时间后整理旧的 Excel 文件。也许您可以在删除文件之前向用户提供指导,让他们的下载 URL 仅在特定小时或天数内有效。这样您的磁盘就不会充满旧的垃圾文件。
推荐阅读
- javascript - 在javascript运行时,堆栈的“帧”和队列的“消息”有什么区别?
- rust - 从通道读取并使用 poll_fn 和 try_ready 的 Tokio 未来永远不会完成
- objective-c - 在什么情况下 [NSDocument fileURL] 可以为零?
- osc - 如何启动和更改 Synth?
- authentication - 漫游到不同 AP 时的身份验证错误
- javascript - Javascript更改事件目标不透明度
- python - 创建具有给定行列的矩阵,但存在输出格式问题
- ios - 如何使用 alamofire 管理器在 ios app swift4 中添加 ssl 证书固定?
- c++ - uintX_t 和 intX_t 类型的打印保证
- sorting - 用拓扑排序在这里找不到问题