感谢Makyen
参考:在 chrome 代码中使用 DOM 文件 API
MDN 声明:var file = File.createFromFileName("path/to/some/file");
以下代码不起作用:(我的误解)
// Using text URL
Components.utils.importGlobalProperties(['File']);
let aFileURL = 'file:///C:/Users/***/icon.png'; // just an example
let file = File.createFromFileName(aFileURL);
// "File error: Unrecognized path" nsresult: "0x80520001 (NS_ERROR_FILE_UNRECOGNIZED_PATH)"
以下代码有效:
Components.utils.importGlobalProperties(['File']);
let aFileURL = 'file:///C:/Users/***/icon.png'; // just an example
let file = Services.io.newURI(aFileURL, null, null)
.QueryInterface(Components.interfaces.nsIFileURL).file; // convert URL to nsIFile
file = File.createFromFileName(file.path);
以下代码也有效:
Components.utils.importGlobalProperties(['File']);
let aFileURL = 'file:///C:/Users/***/icon.png'; // just an example
let file = Services.io.newURI(aFileURL, null, null)
.QueryInterface(Components.interfaces.nsIFileURL).file; // convert URL to nsIFile
file = File.createFromNsIFile(file);
供参考的附加信息:
使用file = new File([], file.path);
产生以下结果:
File { name: "C:\Users\...\icon.png", lastModified: 1487509240391, lastModifiedDate: Date 2017-02-19T13:00:40.391Z, webkitRelativePath: "", mozFullPath: "", size: 0, type: "" }
但是,使用file = File.createFromFileName(file.path);
会产生以下结果:
File { name: "icon.png", lastModified: 1403974172431, lastModifiedDate: Date 2014-06-28T16:49:32.431Z, webkitRelativePath: "", mozFullPath: "", size: 4294, type: "image/png" }
使用file = File.createFromNsIFile(file);
产生以下结果:
File { name: "icon.png", lastModified: 1403974172431, lastModifiedDate: Date 2014-06-28T16:49:32.431Z, webkitRelativePath: "", mozFullPath: "C:\Users\...\icon.png", size: 4294, type: "image/png" }
file
从第一个代码传递到FileReader()
产生错误的结果。"data:application/octet-stream;base64,"
file
从第二个和第三个代码传递来FileReader()
产生正确的结果。
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAQjUlEQVR42uWbB3QU17nHv7uzq60S6sJGotniARGYUCQcZAvkhh0QosZgXPJsHwgJpiTB4Aq4JrafwTHvkZeYBBt4EELAGAwGhABjwEYgcMExEk1CjSIJaXuZyXdHO8v..."