如何将本地URI转换为路径?

时间:2014-07-18 04:42:20

标签: javascript firefox-addon firefox-addon-restartless

如何将本地(文件系统)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"

1 个答案:

答案 0 :(得分:5)

支持的方式实际上就是您已经在做的事情。如果你发现它太冗长,请给自己写一个辅助函数。当然,你可以使用各种助手来缩短它。

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;
相关问题