XMLHttpRequest 是否接受文件协议? [英] Does XMLHttpRequest accept the file protocol?

查看:64
本文介绍了XMLHttpRequest 是否接受文件协议?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个需要将本地设备上的文件转换为 javascript File 对象或 Blob 的 React Native 应用程序,但它有一个使用 file://协议的地址.根据这篇媒体文章,你可以使用 XMLHttpRequest 将 URI 转换为 Blob:

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);
   });
}

我想知道这是怎么可能的,如果有人可以给出解释,考虑到 URI 不使用 HTTP 协议?根据我能找到的任何文档,XMLHttpRequest 仅用于对服务器的 HTTP 请求?

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?

推荐答案

XHR 将请求的模式设置为CORS" [ 永久链接, templink ]

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

所以只允许 (permalink)

So are allowed only (permalink)

  • same-origin requests (includes blob:// scheme). [templink]
  • data:// schemes [templink]
  • HTTP(s)-schemes [templink ]

现在,浏览器并不都同意 file:// 来源应该如何相互关联.有些像 Chrome 会认为它是 opaque-origin,因此永远不会将它视为 same-origin 并且您将无法在此浏览器中从该方案中获取*.
在 Firefox 中,他们会认为 FileSystem 中同目录或更深层的任何资源都是 same-origin,因此您可以在那里获取它.
此外,有些有可用的安全提升,它们可能会允许脚本访问它,例如使用 --allow-file-access-from-files 将允许来自 file:// 方案的请求执行此类请求.

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.

这篇关于XMLHttpRequest 是否接受文件协议?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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