DataTransferItem.getAsFile()
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
如果 DataTransferItem
是一个文件,那 DataTransferItem.getAsFile()
方法将返回拖拽项数据的 File
对象。如果拖拽项的数据不是一个文件,则返回 null
.
语法
File = DataTransferItem.getAsFile();
参数
无。
返回值
例子
下面这个例子中使用 getAsFile()
。放在 drop
事件处理里面。
js
function drop_handler(ev) {
console.log("Drop");
ev.preventDefault();
var data = event.dataTransfer.items;
for (var i = 0; i < data.length; i += 1) {
if (data[i].kind == "string" && data[i].type.match("^text/plain")) {
// 遍历拖拽项的内容
data[i].getAsString(function (s) {
ev.target.appendChild(document.getElementById(s));
});
} else if (data[i].kind == "string" && data[i].type.match("^text/html")) {
// 拖拽项的数据是 HTML
console.log("... Drop: HTML");
} else if (
data[i].kind == "string" &&
data[i].type.match("^text/uri-list")
) {
// 拖拽项的数据是 URI
console.log("... Drop: URI");
} else if (data[i].kind == "file" && data[i].type.match("^image/")) {
// 拖拽项的数据是一个图片
var f = data[i].getAsFile();
console.log("... Drop: File ");
}
}
}
规范
Specification |
---|
HTML # dom-datatransferitem-getasfile-dev |
浏览器兼容性
Report problems with this compatibility data on GitHubdesktop | mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
getAsFile |
Legend
Tip: you can click/tap on a cell for more information.
- Full support
- Full support
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.