Blob:type 属性

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since January 2020.

备注: 此特性在 Web Worker 中可用。

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">选择图片文件……</output>

JavaScript

js
// 我们的程序只允许 GIF、PNG 和 JPEG 类型的图片
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 = "选择图片文件…";
    return;
  }

  const allAllowed = Array.from(files).every((file) =>
    allowedFileTypes.includes(file.type),
  );
  output.innerText = allAllowed ? "所有文件都符合!" : "请只选择图片文件。";
});

结果

规范

Specification
File API
# dfn-type

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
Node.js
type

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
Has more compatibility info.

参见