javascript 如何将本地 URI 转换为路径?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24817347/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you convert a local URI to path?
提问by erosman
How do you convert a local (filesystem) URI to path?
It can be done with nsIIOService+ newURI()+ QueryInterface(Components.interfaces.nsIFileURL)+ file.pathbut that seems like a long way.
Is there a shorter way?
如何将本地(文件系统)URI 转换为路径?
这是可以做到的nsIIOService+ newURI()+ QueryInterface(Components.interfaces.nsIFileURL)+ file.path,但是这似乎是一个很长的路要走。
有没有更短的方法?
Here is an example code:
这是一个示例代码:
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"
回答by nmaier
The supported way is actually what you're already doing. Write yourself a helper function if you find it too verbose. Of course, you can shorten it a bit using the various helpers.
支持的方式实际上是你已经在做的。如果您觉得它太冗长,请为自己编写一个辅助函数。当然,您可以使用各种帮助程序将其缩短一点。
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;
Or:
或者:
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;

