如何将本地URI转换为路径

How do you convert a local URI to path?

本文关键字:转换 路径 URI      更新时间:2023-09-26

如何将本地(文件系统)URI转换为路径?
它可以用nsIIOService + newURI() + QueryInterface(Components.interfaces.nsIFileURL) + file.path来完成,但这似乎是一个很长的路。有近一点的路吗?

下面是一个示例代码:
var aFileURL = 'file:///C:/path-to-local-file/root.png';
var ios = Components.classes["@mozilla.org/network/io-service;1"]
              .getService(Components.interfaces.nsIIOService);
var url = ios.newURI(aFileURL, null, null); // url is a nsIURI
// file is a nsIFile    
var file = url.QueryInterface(Components.interfaces.nsIFileURL).file;
console.log(file.path); // "C:'path-to-local-file'root.png"

支持的方式实际上是您已经在做的。如果觉得太啰嗦,可以自己编写一个helper函数。当然,您可以使用各种帮助程序将其缩短一点。

const {classes: Cc, interfaces: Ci, utils: Cu} = Components;
Cu.import("resource://gre/Services.jsm");
var aFileURL = 'file:///C:/path-to-local-file/root.png';
var path = Services.io.newURI(aFileURL, null, null).
           QueryInterface(Ci.nsIFileURL).file.path;

或:

const {classes: Cc, interfaces: Ci, utils: Cu} = Components;
Cu.import("resource://gre/modules/NetUtil.jsm");
var aFileURL = 'file:///C:/path-to-local-file/root.png';
var path = NetUtil.newURI(aFileURL).QueryInterface(Ci.nsIFileURL).file.path;