首页 > 解决方案 > 如何在 expo 中使用 XmlHttpRequest 读取 ios 设备中的本地文件?

问题描述

我已经处理这个问题3天了。事情是这样的,在 iOS 中我无法使用XmlHttpRequest. 我的代码来自世博会的 firebase-storage-upload-example(链接)。我已将此代码添加到我的 app.json 中:

 {
   "expo": {
     ...somestuf
     "ios": {
       "infoPlist": {
          "NSFaceIDUsageDescription": "This app uses the camera to scan barcodes on event tickets.",
          "NSAppTransportSecurity": {
            "NSAllowsArbitraryLoads": true
          }
      }
     }
 }

在android中一切正常。在 iOS 中,我认为这是一个许可问题,但我不确定。这是代码和错误:

const blob = await new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.onload = () => {
          resolve(xhr.response);
        };
        xhr.onerror = (e) => {
          console.log(e);
          updateStorageLoader({ error: e, loading: false });
          reject(new TypeError('Network Request Failed!'));
        };
        xhr.responseType = 'blob';
        xhr.open('GET', uri, true);
        xhr.send(null);
      });

错误:Network Request Failed!。我该如何解决这个问题?FileSystem.readAsStringAsync(fileUri, options)此方法不是一个选项,因为它不适用于 Firebase 存储上传。

编辑: 我认为这不是权限问题。我已经下载了最新的 expo firebase 上传文件示例,该文件在新创建的配置为 0 的托管工作流应用程序上运行良好。所以我也愿意接受任何提示而不是直接回答。只要您能指出我将不胜感激的事情。

标签: react-nativexmlhttprequestexpofirebase-storage

解决方案


在发布到 Firebase 存储时,使用此处提到的 Buffer 包可以替代 XMLHttpRequest。

这是我用来让 with-firebase-storage-upload 用于第二次和后续上传的代码

import { Buffer } from "buffer"; // get this via: npm install buffer
import * as FileSystem from "expo-file-system";

...

async function uploadImageAsync(uri) {

    const options = { encoding: FileSystem.EncodingType.Base64 };
    const base64Response = await FileSystem.readAsStringAsync(
        uri,
        options,
    );

    const blob = Buffer.from(base64Response, "base64");

    const ref = firebase
        .storage()
        .ref()
        .child(uuid.v4());
    const snapshot = await ref.put(blob);

    return await snapshot.ref.getDownloadURL();
}


推荐阅读