Blob: type 屬性
注意:此功能在 Web Workers 中可用。
Blob 介面的 type 只讀屬性返回檔案的 MIME 型別。
注意:根據當前的實現,瀏覽器並不會真正讀取檔案的位元組流來確定其媒體型別。它會根據副檔名來假設;一個被重新命名為 .txt 的 PNG 影像檔案將返回 "text/plain" 而不是 "image/png"。此外,blob.type 通常只對常見的文件型別(如影像、HTML 文件、音訊和影片)可靠。不常見的副檔名將返回空字串。客戶端配置(例如,Windows 登錄檔)即使對於常見型別也可能導致意外值。建議開發者不要將此屬性作為唯一的驗證方案。
值
包含檔案 MIME 型別的字串,如果無法確定型別,則為空字串。
示例
此示例要求使用者選擇多個檔案,然後檢查每個檔案以確保它是給定的一組影像檔案型別之一。
HTML
html
<input type="file" id="input" multiple />
<output id="output">Choose image files…</output>
JavaScript
js
// Our application only allows GIF, PNG, and JPEG images
const allowedFileTypes = ["image/png", "image/jpeg", "image/gif"];
const input = document.getElementById("input");
const output = document.getElementById("output");
input.addEventListener("change", (event) => {
const files = event.target.files;
if (files.length === 0) {
output.innerText = "Choose image files…";
return;
}
const allAllowed = Array.from(files).every((file) =>
allowedFileTypes.includes(file.type),
);
output.innerText = allAllowed
? "All files clear!"
: "Please choose image files only.";
});
結果
規範
| 規範 |
|---|
| File API # dfn-type |
瀏覽器相容性
載入中…