我一直在尝试调用带有对 Rest API的身份验证的 GET HTTP 请求,以在 Phoenix Live View 页面中下载文件。我调用这个 API 的团队不像其他公司那样有签名 URL,所以我不能只使用window.location=
.
我正在调用的 API 将返回一个Content-Disposition
标头,例如Content-Disposition: attachment; filename*=UTF-8''Q1%20Report.pdf
在我的 LiveView 页面中,我有一个链接,单击后将需要调用此 GET 请求并重定向用户以从浏览器中保存文件。
如果这是一个简单的 JS 页面,我会简单地做这样的事情:
document.getElementById('download').addEventListener('click', function () {
var content = document.getElementById('content').value;
var request = new XMLHttpRequest();
// Add some authorization headers here
request.open('POST', '../server/', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.responseType = 'blob';
request.onload = function() {
// Only handle status code 200
if(request.status === 200) {
// Try to find out the filename from the content disposition `filename` value
var disposition = request.getResponseHeader('content-disposition');
var matches = /"([^"]*)"/.exec(disposition);
var filename = (matches != null && matches[1] ? matches[1] : 'file.pdf');
// The actual download
var blob = new Blob([request.response], { type: 'application/pdf' });
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
// some error handling should be done here...
};
request.send('content=' + content);
});
但是如何使用 LiveView 做到这一点?我在 Phoenix LiveView 文档中进行了搜索,但找不到任何示例。如果你以前做过,你能告诉我怎么做吗?