Cha*_*apo 6 javascript request-headers http-headers fetch-api
我使用以下命令将 zip 文件从 Nodejs 服务器发送到浏览器
res.set("Content-Type", "application/octet-stream");
res.set("Content-disposition", `attachment; filename="`+zip_name+`.zip"`);
res.set("Content-Length", zipBuff.length);
res.send(zipBuff);
Run Code Online (Sandbox Code Playgroud)
然后我使用以下方法获取它:
fetch("/my/url", {
method: "POST",
body: formData,
})
.then(response => {
return response.blob();
})
.then(response => {
const blob = new Blob([response], {type: 'application/zip'});
const downloadUrl = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = downloadUrl;
a.download = "blah.zip";
document.body.appendChild(a);
a.click();
});
Run Code Online (Sandbox Code Playgroud)
我希望能够使用zip_name而不是blah文件名,但我无法弄清楚如何Content-disposition使用fetch.
有人可以解释一下它是如何完成的吗?
返回对象中的 blob 和标头
fetch("/my/url", {
method: "POST",
body: formData,
})
.then(response => {
const headers = response.headers
return { blob: response.blob(), headers }
})
.then(({blob, headers}) => {
/// now you can access to **headers** and blob data
});
Run Code Online (Sandbox Code Playgroud)
要访问标头,请使用headers.get("Header name").split('=').pop()
const foo = async () => {
const response = await fetch("/my/url", {
method: "POST",
body: formData,
})
if(!response.ok)
thorw new Error("Some error happend")
const blod_data = await response.blob()
const header_with_name = response.headers.get("Header name").split('=').pop()
// do something with it
}
Run Code Online (Sandbox Code Playgroud)
在第一个 Promise 箭头函数中,您可以访问 HTTP 响应标头。如果您更新它以从函数调用返回承诺blob。然后,在此嵌套函数中,您可以将包含标头值的对象返回到处理 blob 数据的外部第二个箭头函数。
更新了 fetch 示例,其中包括处理从 blob 函数调用返回的 Promise。
fetch("/my/url", {
method: "POST",
body: formData,
})
.then(response => {
return response.blob().then((data) => {
return {
data: data,
filename: response.headers.get('Content-disposition'),
};
});
})
.then(({ data, filename }) => {
const blob = new Blob([data], { type: 'application/zip' });
const downloadUrl = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = downloadUrl;
a.download = filename.split('=')[1];
document.body.appendChild(a);
a.click();
});
Run Code Online (Sandbox Code Playgroud)
谢谢 Chapo 指出我之前例子的问题