How do you convert a local URI to path?

给你一囗甜甜゛ 提交于 2019-12-07 19:46:26

问题


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"

回答1:


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;


来源:https://stackoverflow.com/questions/24817347/how-do-you-convert-a-local-uri-to-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!