以下代码创建 JavaScript 并创建一个包含类型化链接列表中的数据的新 blob。 然后调用 URL.createObjectURL() 方法将 blob 转换为 URL。
超文本标记语言
html
<p>
此示例创建一个类型化数组,其中包含空格以及 A 到 Z 的 ASCII
字符。然后将其转换为一个对象 URL。并创建一个打开该对象 URL
的链接。点击这个链接以查看对象 URL 解码后的内容。
</p>
JavaScript
此示例代码片段的主要部分是 typedArrayToURL() 函数,该函数根据给定的类型化字段创建一个 blob 并返回该 blob 的对象 URL。一旦数据转换为对象 URLcss文件格式,就可以以多种形式使用它,包括:如
元素属性的值(当然css文件格式,假设给定数据包含图像)。
js
function showViewLiveResultButton() {
if (window.self !== window.top) {
// 如果当前文档是否在一个 frame 中,则
// 确保让用户在新的标签页或窗口中打开它。
// 否则,此示例将无法正常演示。
const p = document.querySelector("p");
p.textContent = "";
const button = document.createElement("button");
button.textContent = "查看上面示例代码的渲染结果";
p.append(button);
button.addEventListener("click", () => window.open(location.href));
return true;
}
return false;
}
if (!showViewLiveResultButton()) {
function typedArrayToURL(typedArray, mimeType) {
return URL.createObjectURL(
new Blob([typedArray.buffer], { type: mimeType }),
);
}
const bytes = new Uint8Array(59);
for (let i = 0; i < 59; i++) {
bytes[i] = 32 + i;
}
const url = typedArrayToURL(bytes, "text/plain");
const link = document.createElement("a");
link.href = url;
link.innerText = "打开这个数组的 URL";
document.body.appendChild(link);
}
结果