3

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"
erosman
  • 7,094
  • 7
  • 27
  • 46
  • Can you show example of what you're starting with and what you want to end up with. Optional: Also a snippet to show how you currently do it. – Noitidart Jul 18 '14 at 05:00
  • Ah cool question, you're trying to turn it into a path you can feed the [`DOMFile`](https://developer.mozilla.org/en/Extensions/Using_the_DOM_File_API_in_chrome_code) API right? – Noitidart Jul 18 '14 at 06:07
  • @Noitidart I want to use it for file upload as per my other 2 questions – erosman Jul 18 '14 at 07:34

1 Answers1

6

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;
nmaier
  • 32,336
  • 5
  • 63
  • 78
  • 1
    Please note: `var path = Services.io.newURI(aFileURL, null, null).QueryInterface(Ci.nsIFileURL).file.path;` results in error (since file doesn't exist) ... it should be: `var file = Services.io.newURI(aFileURL, null, null).QueryInterface(Ci.nsIFileURL).file.path;` ... the value of `file` is now the `path`. it is the same with the next one too ;) – erosman Jul 25 '14 at 18:04