Laravel Excel 使用 Ajax 请求,没办法下载如何处理?(有方案)[vue][axios][Excel]

在使用 element-ui 开发的过程中,有需求时需要导出excel报表的。

选择的(laravel excel)[https://github.com/Maatwebsite/Laravel-Exc...] 处理导出,但是发现通过ajax的请求,都不会成功的下载。

查找了资料,发现如下几个方案:

  1. axios 增加 responseType:arraybuffer。 参考
    尝试未生效
  2. 保存在服务器,然后前端请求下载
    未尝试,应该可行。

    I was able to solve the problem. I'm using 'store' method to save the file on the server, and then I send the response (the path to the file):

    export.done(function (data) {
    window.location.href = data;
    });

    And the file can be donwloaded.

  3. 直接在新窗口打开,可以成功下载 尝试可行,需重新拼接url
    • window.location.href= queryString;
  4. laravel 返回json数据,然后模拟自动点击a标签下载 参考
    $myFile= Excel::create("filename", function($excel) use($data) {
    $excel->setTitle('title');
    $excel->sheet('sheet 1', function($sheet) use($data) {
     $sheet->fromArray($data, null, 'A1', true, true);
    });
    });
    $myFile = $myFile->string('xlsx'); //change xlsx for the format you want, default is xls
    $response =  array(
    'name' => "filename", //no extention needed
    'file' => "data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,".base64_encode($myFile) //mime type of used format
    );
    return response()->json($response);

    ajax 内容:

    $.ajax({
      cache: false,
      url: url, //GET route 
      data:  params, //your parameters data here
      success: function (response, textStatus, request) {
        var a = document.createElement("a");
        a.href = response.file; 
        a.download = response.name;
        document.body.appendChild(a);
        a.click();
        a.remove();
      },
      error: function (ajaxContext) {
        toastr.error('Export error: '+ajaxContext.responseText);
      }
    });

问题如下:
有遇到过类似问题的吗,一般使用什么方法解决?
现在有导入excel,如果有不符合的数据,需要导出,要怎么处理,选择方案2?
有其他方法的欢迎补充~

《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 10

我的方案是不用 ajax, 直接拼一个 GET 请求的接口, 也就是一个 url, 然后 Excel::create()->download('xlsx);

6年前 评论

@小恪守 这个应该是比较便捷的方案了

6年前 评论

可以先给一个url, 然后通过这个url下载;

6年前 评论

@猪爷爷 果然还是不能直接请求下载,网上找了半天

6年前 评论

@猪爷爷 不能是个url,,url任何人都能下载,,最好是个下载的接口,,这样能控制权限...

5年前 评论

ajax成功后,在success中使用window.location.href = ''试试

4年前 评论

可以看下我写的ajax下载文件的,希望对你有帮助 博客:Ajax 下载文件

4年前 评论

@limin 接口中怎么返回excel文件呢

4年前 评论
leo

应该是用 responseType:blob https://github.com/axios/axios/issues/448#...

4年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!