我正在开发一项功能,使用户能够下载 PNG 和 JSON。经过研究,我利用window.showSaveFilePicker方法来方便下载JSON文件。对于 PNG 文件,我生成了一个数据 URL 并将其链接到锚元素的 href 属性。通过触发点击事件,我成功启用了PNG文件的下载。这种方法被认为更适合 PNG 文件,因为它源自画布元素,允许使用
canvas.toDataURL("image/PNG")
轻松转换。实现这两种方法让我开始考虑一种方法是否比另一种方法更有效地下载文件。
两种下载的代码如下:
async function saveJSON() {
const blob = new Blob([
JSON.stringify({
/* object here */
}, null, 2)
], {
type: "application/json"
});
const newHandle = await window.showSaveFilePicker({
types: [{
description: "Some description",
accept: {
"application/json": [ "application/json" ]
},
}],
id: "save-json-file-picker",
excludeAcceptAllOption: true,
});
const writableStream = await newHandle.createWritable();
await writableStream.write(blob);
await writableStream.close();
}
function savePNG() {
const canvas = document.createElement("canvas");
// Logic to create the image in the canvas element goes here
const url = canvas.toDataURL("image/png");
const a = document.createElement('a')
a.href = url;
a.download = 'image.png';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
两种方法都按预期工作。
使用
createWritable()
无需创建数据 URL,因此文件系统访问 API。
使用文件 API 适用于基于 Chromium 的浏览器以外的浏览器。由于其自身原因,Firefox 没有实现 WICG 文件系统访问 API。