【问题标题】:How do you convert a local URI to path?如何将本地 URI 转换为路径?
【发布时间】:2014-07-18 04:42:19
【问题描述】:

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

【问题讨论】:

  • 您能否举例说明您开始使用的内容和想要结束的内容。可选:还有一个 sn-p 以显示您当前的操作方式。
  • 啊,很酷的问题,你想把它变成一条可以提供DOMFile API 的路径,对吧?
  • @Noitidart 根据我的其他 2 个问题,我想用它来上传文件

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


【解决方案1】:

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

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;

【讨论】:

  • 请注意:var path = Services.io.newURI(aFileURL, null, null).QueryInterface(Ci.nsIFileURL).file.path; 导致错误(因为文件不存在)...应该是:var file = Services.io.newURI(aFileURL, null, null).QueryInterface(Ci.nsIFileURL).file.path; ...file 的值现在是path .下一个也一样;)
猜你喜欢
  • 2017-08-09
  • 2014-04-27
  • 2011-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-04
  • 2015-02-22
  • 1970-01-01
相关资源
最近更新 更多