从Laravel后端使用Axios下载Excel数据无法正常工作

时间:2018-07-31 14:11:14

标签: excel reactjs laravel axios

我正在使用前端的React JS和后端的API的Laravel开发一个Web应用程序。现在,我正在尝试使用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')
        })
    }

如您在上面的代码中看到的,如果请求成功,它应该警告消息“一切都很好”。但是它不会警告消息。但是在浏览器中,它是成功的。

enter image description here

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

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

2 个答案:

答案 0 :(得分:0)

您只需使用window.open(path)即可下载文件

答案 1 :(得分:0)

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

  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;