你如何将本地URI转换为路径? [英] How do you convert a local URI to path?

查看:177
本文介绍了你如何将本地URI转换为路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将本地(文件系统)URI转换为路径?

可以使用 nsIIOService + newURI () + QueryInterface(Components.interfaces.nsIFileURL) + file.path 似乎有很长的路要走。
有没有更简单的方法?

How do you convert a local (filesystem) URI to path?
It can be done with nsIIOService + newURI() + QueryInterface(Components.interfaces.nsIFileURL) + file.path but that seems like a long way.
Is there a shorter way?

以下是一个示例代码:

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"


推荐答案

支持的方式实际上是你已经做的。写一个帮助函数,如果你发现它太冗长。当然,你可以使用各种帮助程序来缩短它。

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;

这篇关于你如何将本地URI转换为路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆