expo-document picker: how to read the file on web?

  1. SDK Version: 49.0.11
  2. Platforms(Android/iOS/web/all): web
    “expo-document-picker”: “~11.5.4”,
    “expo-file-system”: “~15.4.4”,

I am creating an app on react-native, mainly to run on Android (did not try on iOS yet, just ignoring for now). Running it on web has been useful for me to debug. One of the use cases that I did not manage to make work in web but it does in Android is uploading a file.

The following seems to work on Android, but I did not figure out how to get the file in web:

import * as DocumentPicker from "expo-document-picker";
import { Platform } from "react-native";
import * as ExpoFileSystem from "expo-file-system";

export async function FileUpload() {
  let res = null;
  try {
    res = await DocumentPicker.getDocumentAsync({
      type: "*/*",
      copyToCacheDirectory: true,
      multiple: false,
    });
    if (res.canceled) {
      return;
    }

    let fileContent = null;
    if (Platform.OS === "android") {
      fileContent = await ExpoFileSystem.readAsStringAsync(
        res.assets[0].uri,
        { encoding: ExpoFileSystem.EncodingType.UTF8 }
      );
    } else if (Platform.OS === "web") {
      // TODO: how to read the file using the uri?
      console.log("TODO: implement read file for web");
      const file = res.assets[0].file;
      console.log(file);

      // in https://github.com/expo/expo/issues/21792
      // I was given this code, but not sure what to write in the headers or what's the url...
      const requestData = new FormData();
      requestData.append("file", file);

      const options = {
        method: "POST",
        body: requestData,
        headers: headers,
      };

      const response = await fetch(url, options);
    }
    if (fileContent === null || fileContent === undefined) {
      console.log("fileContent is null or undefined");
      return;
    }

   // process the uploaded file
    try {
      fileContent = JSON.parse(fileContent);
    } catch (err) {
      console.log("error parsing json");
      console.log(err);
      return;
    }
    return fileContent;
  } catch (err) {
    console.log("error -----", err);
  }
}

Can anybody help?

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.