我正在开发拖放上传功能。通过 drop 事件,我使用 e.dataTransfer.items 检索所有文件和文件夹的句柄,然后调用 items[n].webkitGetAsEntry() 方法来获取 FileEntry 对象。最后,我尝试使用 FileEntry.file((file) => {}) 方法从回调中检索文件对象:
function traverseFileTree(item, path = "") {
// The item here is the return value of webkitGetAsEntry().
const isRecursive = document.getElementById("recursiveOption").checked;
if (item.isFile) {
item.file(
(file) => {
console.log("file", file);
if (file.name.toLowerCase().endsWith(".md")) {
file.fullPath = path + file.name;
files.push(file);
updateFileList();
}
},
(error) => {
console.error(error);
showPopup(`Failed to read file ${item.name}: ${error.message}`);
}
);
} else if (item.isDirectory) {
if (isRecursive || path === "") {
let dirReader = item.createReader();
dirReader.readEntries(
(entries) => {
for (let i = 0; i < entries.length; i++) {
traverseFileTree(entries[i], path + item.name + "/");
}
},
(error) => {
console.error("Failed to read directory:", error);
showPopup(`Failed to read directory ${item.name}: ${error.message}`);
}
);
}
}
}
但是,奇怪的事情发生了:当我直接在浏览器中打开 HTML 文件(使用文件协议)时,.file() 方法抛出 EncodingError: 文件:
EncodingError: A URI supplied to the API was malformed, or the resulting Data URL has exceeded the URL length limitations for Data URLs.
但是,当我通过本地服务器(例如,使用 HTTP 上的 Live Server)提供相同的 HTML 文件时,.file() 方法按预期工作,我可以成功检索文件对象。 http:
我搜索了各种资源并咨询了 GPT,但找不到明确的答案。我怀疑该问题可能与浏览器安全策略或相对路径限制有关。有谁遇到过这个问题或者知道可能是什么原因造成的吗?
我希望: 了解这个问题的具体原因。 以后类似的问题我该如何自己解决?
谢谢!
file://
协议在大多数浏览器中都受到严格限制,尤其是 Chrome。 这是出于安全考虑,尽管我找不到有关此特定问题的文档(该错误也相当迟钝)。
具体限制取决于所使用的 API,因此请尝试使用不同的 API。例如,不要使用
dataTransferItem.webkitGetAsEntry()
,而是尝试使用 dataTransferItem.getAsFile()
,这样您甚至可以在 file://
上访问文件名(和大小)。