【问题标题】:Downloading Excel data using Axios from Laravel backend is not working从 Laravel 后端使用 Axios 下载 Excel 数据不起作用
【发布时间】:2019-01-07 23:17:50
【问题描述】:

我正在开发一个 Web 应用程序,前端使用 React JS,后端 API 使用 Laravel。现在,我要做的是尝试使用 Axios 从后端获取 Excel 数据,然后下载文件。

这是我的 Laravel API 控制器操作方法。

function downloadExcel(Request $request)
{
    //other code goes here
    return Excel::create($left_photo->id . "-" . $right_photo->id, function($excel) use ($excel_data)
        {

            // Set the spreadsheet title, creator, and description
            $excel->setTitle('Mapping points');
            $excel->setCreator('Laravel')->setCompany('Memento');
            $excel->setDescription('Mapping points file');

            // Build the spreadsheet, passing in the payments array
            $excel->sheet('sheet1', function($sheet) use ($excel_data)
            {
                $sheet->fromArray($excel_data, null, 'A1', false, false);
            });

        })->download('xlsx');
}

我像这样使用 Axios 从 react js 应用程序中获取数据。

export const getHttpClientFileDownload = (path) => {
  let accessToken = localStorage.getItem("access_token");
  return Axios({
    url: getApiBaseEndpoint() + path,
    method: 'GET',
    responseType: 'blob', // important
    headers : { 'api-version': API_VERSION, 'Authorization': 'Bearer ' + accessToken }
  })
}

exportExcel()//this is the download medthod in the component
    {
        let path = 'photos/matching-points/excel?left_photo_id=' + this.props.leftImageId + "&right_photo_id=" + this.props.rightImageId;
        //let path = "curator/event/" +this.props.match.params.id + "/details";
        getHttpClientFileDownload(path)
        .then((response) => {
            alert('Everything is alright')
        })
    }

正如您在上面的代码中看到的,如果请求成功,它应该会提示一条消息,“一切正常”。但它并没有提醒消息。但是在浏览器中,是成功的。

当我向仅返回正常 JSON 响应的链接发出请求时,它会按预期警告消息。只有当我向上述 Excel API 发出请求时,它没有按预期工作。

我无法使用直接下载链接,因为我正在服务器端进行一些授权。

【问题讨论】:

    标签: excel reactjs laravel axios


    【解决方案1】:

    我遇到了同样的问题,并找到了如下解决方案。 步骤:

    1. 调用 API 到 Laravel 后端。创建文件并将其存储在服务器上的本地驱动程序中。
    2. 将文件名返回给客户端。
    3. 在 Laravel(在 web.php 中)创建一个公共路由以从本地存储下载文件。此路由会在下载后删除文件。
    4. 从客户端,使用文件名将用户重定向到此公共 URL。

    我的代码如下所示。我使用了获取 API。 客户端代码:

    const response = await fetch("my_server_url.com/api/createFile", {
                        method: 'GET',
                        headers: {
                            Authorization: "Bearer " + this.$store.state.AccessToken,
                            "X-Requested-With": "XMLHttpRequest",
                        },
                    });
    
                    if (!response.ok) {
                        console.log(response)
                        throw new Error("Something went wrong!");
                    }
    
                    const data = await response.json();
                    window.open("my_server_url.com/downloadFile/name="+data, '_blank');
    

    my_server_url.com/api/createFile 路由中的代码:(api.php)

    public function createFile()
        {
            $file_name= date('YmdHis').rand();
            Excel::store(new myExport(), $file_name.'.xlsx', 'local');
    
            return response()->json($file_name.'.xlsx', 200);
        }
    

    my_server_url.com/downloadFile/name={file_name} 路由中的代码:(web.php)

    public function downloadFile($file_name)
        {
            return response()->download(Storage::path($file_name))->deleteFileAfterSend(true);
        }
    

    这样,您可以检查授权和逻辑,但仍需使用 API。另外,请确保在 laravel 控制器中添加use Illuminate\Support\Facades\Storage;

    【讨论】:

      【解决方案2】:

      你可以简单地使用 window.open(path) 来下载文件

      【讨论】:

      • 我无法使用直接下载链接,因为我正在服务器端进行一些授权
      猜你喜欢
      • 2021-08-25
      • 1970-01-01
      • 2019-09-19
      • 2021-10-28
      • 2021-08-31
      • 2013-10-27
      • 2021-09-16
      • 2023-01-21
      • 1970-01-01
      相关资源
      最近更新 更多