【发布时间】: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