How to read local file in ios devices by using XmlHttpRequest in expo?

早过忘川 提交于 2020-12-15 07:04:08

问题


I've been dealing with this problem for 3 days. Here is the thing, in iOS I cannot read file by using XmlHttpRequest. My code is from expo's firebase-storage-upload-example (link). I've added this code to my app.json:

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

In android everything works fine. In iOS I think it's a permission kinda issue but I'm not sure. Here is the code and error:

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

Error: Network Request Failed!. How can I resolve this? FileSystem.readAsStringAsync(fileUri, options) this method is not an option because it's not working with firebase storage upload.

Edit: I think that it's not an issue with permissions. I've downloaded the latest example of expo firebase upload file, which is working totally fine on newly created managed worklflow app with 0 configuration. So I'm open to any hint instead of direct answer as well. Just if you could point out that something I will be appreciated.


回答1:


Using the Buffer package mentioned here works as a replacement for XMLHttpRequest when posting to firebase storage.

Here is the code I used to get with-firebase-storage-upload working for 2nd and subsequent uploads

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


来源:https://stackoverflow.com/questions/64098886/how-to-read-local-file-in-ios-devices-by-using-xmlhttprequest-in-expo

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