0

I am trying to make a react native application that requires converting a file on the local device into a javascript File object or Blob, but it has an address using the file:// protocol. According to this Medium article, you can use XMLHttpRequest to turn the URI into a Blob:

uriToBlob = (uri) => {
   return new Promise((resolve, reject) => {
      const xhr = new XMLHttpRequest();
      xhr.onload = function() {
         // return the blob
         resolve(xhr.response);
      };

      xhr.onerror = function() {
      // something went wrong
      reject(new Error('uriToBlob failed'));
   };

   // this helps us get a blob
   xhr.responseType = 'blob';
   xhr.open('GET', uri, true);

   xhr.send(null);
   });
}

I am wondering how this is possible and if someone could give an explanation, considering that the URI doesn't use HTTP protocol? According to whatever documentation I could find, XMLHttpRequest is only used for HTTP requests to a server?

Victor Hu
  • 21
  • 3

2 Answers2

0

Documentation: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest

Reference the section on "Handling binary data"

You can use it against file: but progress listeners are not supported... so you'll only be able to trigger on load, error, and abort

DynasticSponge
  • 1,416
  • 2
  • 9
  • 13
  • The file is located on a local device, not on a server. My question boils down to if/how XMLHttpRequest can take File:// URI's instead of HTTP URL's, since it never seems to be mentioned in the documentation. I'm not concerned with whether or not it is read as binary or textual data. – Victor Hu Jul 31 '20 at 05:44
0

XHR sets the request's mode to "CORS" [ permalink, templink ]

So are allowed only (permalink)

Now, browsers don't all agree as to how file:// origins should relate with each others. Some like Chrome will consider it an opaque-origin, and will thus never treat it as same-origin and you won't be able to fetch from this scheme in this browser*.
In Firefox, they will consider that any resource in the same directory or deeper in the FileSystem is same-origin, so there you can fetch it.
Also, some have security lifts available where they may exceptionally allow scripts to access it, for instance starting Chrome with the --allow-file-access-from-files will allow requests from a file:// scheme to perform such requests.

Kaiido
  • 123,334
  • 13
  • 219
  • 285