如果我想下载文件,我应该在下面的then
块中做什么?
function downloadFile(token, fileId) {
let url = `https://www.googleapis.com/drive/v2/files/${fileId}?alt=media`;
return fetch(url, {
method: 'GET',
headers: {
'Authorization': token
}
}).then(...);
}
请注意,代码位于客户端。
答案 0 :(得分:43)
这更短,更有效,没有库仅获取API
const url ='http://sample.example.file.doc'
const authHeader ="Bearer 6Q************"
const options = {
headers: {
Authorization: authHeader
}
};
fetch(url, options)
.then( res => res.blob() )
.then( blob => {
var file = window.URL.createObjectURL(blob);
window.location.assign(file);
});
答案 1 :(得分:33)
编辑:syg答案更好。只需使用downloadjs库。
我提供的答案适用于Chrome,但在Firefox和IE上,您需要使用此代码的一些不同变体。最好使用库。
我有类似的问题(需要传递授权标头才能下载文件,因此this解决方案没有帮助。)
但根据this回答,您可以使用createObjectURL
使浏览器保存由Fetch API下载的文件。
getAuthToken()
.then(token => {
fetch("http://example.com/ExportExcel", {
method: 'GET',
headers: new Headers({
"Authorization": "Bearer " + token
})
})
.then(response => response.blob())
.then(blob => {
var url = window.URL.createObjectURL(blob);
var a = document.createElement('a');
a.href = url;
a.download = "filename.xlsx";
document.body.appendChild(a); // we need to append the element to the dom -> otherwise it will not work in firefox
a.click();
a.remove(); //afterwards we remove the element again
});
});
答案 2 :(得分:3)
这里是一个使用node-fetch的示例,用于发现此错误的任何人。
reportRunner({url, params = {}}) {
let urlWithParams = `${url}?`
Object.keys(params).forEach((key) => urlWithParams += `&${key}=${params[key]}`)
return fetch(urlWithParams)
.then(async res => ({
filename: res.headers.get('content-disposition').split('filename=')[1],
blob: await res.blob()
}))
.catch(this.handleError)
}
答案 3 :(得分:1)
function download(dataurl, filename) {
var a = document.createElement("a");
a.href = dataurl;
a.setAttribute("download", filename);
a.click();
return false;
}
download("data:text/html,HelloWorld!", "helloWorld.txt");
或:
function download(url, filename) {
fetch(url).then(function(t) {
return t.blob().then((b)=>{
var a = document.createElement("a");
a.href = URL.createObjectURL(b);
a.setAttribute("download", filename);
a.click();
}
);
});
}
download("https://get.geojs.io/v1/ip/geo.json","geoip.json")
download("data:text/html,HelloWorld!", "helloWorld.txt");
答案 4 :(得分:1)
使用dowloadjs。这将从标题中解析文件名。
fetch("yourURL", {
method: "POST",
body: JSON.stringify(search),
headers: {
"Content-Type": "application/json; charset=utf-8"
}
})
.then(response => {
if (response.status === 200) {
filename = response.headers.get("content-disposition");
filename = filename.match(/(?<=")(?:\\.|[^"\\])*(?=")/)[0];
return response.blob();
} else {
return;
}
})
.then(body => {
download(body, filename, "application/octet-stream");
});
};
答案 5 :(得分:0)
我尝试过window.fetch,但最终由于我的REACT应用而变得复杂
现在我只是更改window.location.href并添加jsonwebtoken
和other stuff
之类的查询参数。
///==== client side code =====
var url = new URL(`http://${process.env.REACT_APP_URL}/api/mix-sheets/list`);
url.searchParams.append("interval",data.interval);
url.searchParams.append("jwt",token)
window.location.href=url;
// ===== server side code =====
// on the server i set the content disposition to a file
var list = encodeToCsv(dataToEncode);
res.set({"Content-Disposition":`attachment; filename=\"FileName.csv\"`});
res.status(200).send(list)
最终结果实际上是非常好的,窗口发出请求并下载文件,并且事件切换没有将页面移开,好像window.location.href
调用就像是低调的{{1} }。
答案 6 :(得分:0)
IMO 类似但更干净、更可靠的解决方案。
在您的提取功能上...
fetch(...)
.then(res =>
{
//you may want to add some validation here
downloadFile(res);
}
)
而downloadFile函数是...
async function downloadFile(fetchResult) {
var filename = fetchResult.headers.get('content-disposition').split('filename=')[1];
var data = await fetchResult.blob();
// It is necessary to create a new blob object with mime-type explicitly set
// otherwise only Chrome works like it should
const blob = new Blob([data], { type: data.type || 'application/octet-stream' });
if (typeof window.navigator.msSaveBlob !== 'undefined') {
// IE doesn't allow using a blob object directly as link href.
// Workaround for "HTML7007: One or more blob URLs were
// revoked by closing the blob for which they were created.
// These URLs will no longer resolve as the data backing
// the URL has been freed."
window.navigator.msSaveBlob(blob, filename);
return;
}
// Other browsers
// Create a link pointing to the ObjectURL containing the blob
const blobURL = window.URL.createObjectURL(blob);
const tempLink = document.createElement('a');
tempLink.style.display = 'none';
tempLink.href = blobURL;
tempLink.setAttribute('download', filename);
// Safari thinks _blank anchor are pop ups. We only want to set _blank
// target if the browser does not support the HTML5 download attribute.
// This allows you to download files in desktop safari if pop up blocking
// is enabled.
if (typeof tempLink.download === 'undefined') {
tempLink.setAttribute('target', '_blank');
}
document.body.appendChild(tempLink);
tempLink.click();
document.body.removeChild(tempLink);
setTimeout(() => {
// For Firefox it is necessary to delay revoking the ObjectURL
window.URL.revokeObjectURL(blobURL);
}, 100);
}
(downloadFile 函数来源:https://gist.github.com/davalapar/d0a5ba7cce4bc599f54800da22926da2)
答案 7 :(得分:-1)
根据其他一些答案,您绝对可以使用window.fetch和download.js下载文件。但是,将window.fetch与blob结合使用会限制浏览器的内存,而download.js也具有its compatibility restrictions。
如果您需要下载大文件,则不想将其放在客户端的内存中以给浏览器施加压力,对吗?相反,您可能更喜欢通过流下载它。在这种情况下,使用HTML链接下载文件是最好/最简单的方法之一,尤其是通过流下载大文件时。
第一步:创建链接元素并为其设置样式
您可以使链接不可见,但仍可操作。
HTML:
<a href="#" class="download-link" download>Download</a>
CSS:
.download-link {
position: absolute;
top: -9999px;
left: -9999px;
opacity: 0;
}
第二步:设置链接的href
,并触发click
事件
JavaScript
let url = `https://www.googleapis.com/drive/v2/files/${fileId}?alt=media`;
const downloadLink = document.querySelector('.download-link')
downloadLink.href = url + '&ts=' + new Date().getTime() // Prevent cache
downloadLink.click()
注意:您可以根据需要动态生成链接元素。