Attempting to transfer files to and from Firebase storage

Having trouble with my React Native app. I am trying to upload files, whether they are pictures or PDFs, but once uploaded, I can't seem to open them. However, "The files are getting uploaded to the storage."

export const uploadToStorage = async (document: any) => {
  try {
    const storage = getStorage();
    const fileName = document?.name;

    const storageRef = ref(storage, `files/${fileName}`);
    
    const fileRef = ref(storageRef);
    const fileType = document?.mimeType;
    const metaData = {
      contentType: fileType
    };
    const snapshot = await uploadBytesResumable(storageRef, document, metaData);
    console.log('Upload successful:', snapshot);

    const downloadURL = await getDownloadURL(fileRef);
    console.log('Download URL:', downloadURL);
    return downloadURL;
  } catch (error) {
    console.error('Error:', error);
    throw error;
  }
}
 const _pickDocument = async () => {
    const result = await DocumentPicker.getDocumentAsync({
      multiple: false,
    })
    if (result !== null) {
      result.assets?.map(async (item: any) => {
        const filePrefix = 'file://'
        if (item.uri.startsWith(filePrefix)) {
          item.uri = item.uri.substring(filePrefix.length)
        }
        console.log('URL:' + item.mimeType)
        dispatch(addPDF(item.name))
        if (auth.currentUser?.uid !== null) {
          console.log(auth.currentUser?.uid)
          
          await uploadToStorage(item).then((downloadUrl) => {
            setDownloadUrl(downloadUrl)
            
          }) 
        }
      })
    }
  }
service firebase.storage {
  match /b/{bucket}/o {
    // Allow read and write access to all files
    match /{allPaths=**} {
      allow read, write;
    }
  }
}

No luck with different headers/metaData or switching to uploadBytes instead of uploadBytesResumable. The file uploads correctly but is not manually accessible from Firebase Storage.

For example, uploading a PDF results in an error message: Error: Failed to load PDF document.

Answer №1

As per the documentation, when using uploadBytesResumable, you need to provide a data in the form of Blob | Uint8Array | ArrayBuffer. However, it seems that the item/document you are trying to upload is of type DocumentPickerAsset, which is not compatible.

In order to proceed, you should extract the bytes from the File within the asset and then transmit those to Firebase.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to grasp the connections between the any, unknown, {} data types and their relationships with other types?

Seeking to comprehend relationships between different types, the following code is presented: type CheckIfExtends<A, B> = A extends B ? true : false; type T1 = CheckIfExtends<number, unknown>; //true type T2 = CheckIfExtends<number, {}> ...

Selection of a map in React Native using a checkbox

When mapping through an array of objects called abilities in React Native that I retrieve from the backend, I am trying to individually select each one of them. However, when I select one checkbox, it selects all of them. How can I effectively select a s ...

Converting JS carousel to TS for showcasing multiple items

I am currently working on integrating a bootstrap carousel into my Angular project and I need to convert my JavaScript file to a TypeScript file. As someone who is new to this, I'm unsure of the process for converting and implementing it in a .ts file ...

What is the contrast between element.getAttribute() value and a String in protractor?

When using protractor and typescript, I need to verify that the text saved in a textbox matches a certain string by comparing it with the resulting value of element.getAttribute("value"). Unfortunately, getText() does not work for this scenario b ...

Enhancing TypeScript Data Objects

I'm looking to expand a data object in TypeScript by introducing new fields. Although I know it's a common practice in JavaScript, I'm struggling to get it to compile without making bar optional in the provided snippet. I am interested in f ...

Classbased Typescript implementation for managing state with a Vuex store

Hey everyone, I'm currently working on a Vue project with Vuex using decorators for strong typing in my template. As someone new to the concept of stores, I am struggling to understand how to properly configure my store to work as expected in my comp ...

The Vue CLI project, using Typescript, is facing challenges with building and running Mocha tests

My Vue 2 project, created using Vue CLi, is encountering numerous errors. While it compiles fine for development purposes, running unit tests or building for production results in a cascade of issues. Displayed below are some sample errors, along with sni ...

What is the best way to dynamically insert values into a JSON object?

I'm currently working with a JSON object in Angular and I need to dynamically add values that the user enters. Despite searching extensively, I haven't found a straightforward method to achieve this. I simply want to understand how to append key- ...

`A bug in my Angular 4 application causes a TypeError when hosted on IIS`

After hosting an Angular 4 app on IIS, it seems there is an issue when accessing the app from machines other than the ones used for development. An error message " 'Uncaught TypeError: undefined is not a function' common.es5.js:3084" appears on t ...

Ways to confirm the visibility of a web element on the screen with serenity-js

In the current project, I am utilizing the Serenity-js BDD framework with a screenplay pattern approach. However, I am encountering an issue when attempting to assert the visibility of an element on a web page using the "that" method from the Ensure class. ...

What is the best way to declare a TypeScript type with a repetitive structure?

My data type is structured in the following format: type Location=`${number},${number};${number},${number};...` I am wondering if there is a utility type similar to Repeat<T> that can simplify this for me. For example, could I achieve the same resul ...

Efficient ways to manage dropdown cells in ReactGrid

Is there a way to assign individual values to each select element in a cell? I am using ReactGrid with react version 16 There seems to be an issue with the onchange function, and I'm struggling to find help import * as React from "react"; ...

The dragging and dropping feature for HTML input type="file" is not functioning properly in Edge and IE11

I've developed an Angular app using this sample where I have included only an input control on the screen. Within my project, I constructed a custom file-uploader component. While I am able to drag and drop files in Chrome, I encountered issues with d ...

Verification for collaborative element

I am currently working on creating a shared component for file uploads that can be reused whenever necessary. Interestingly, when I include the file upload code in the same HTML as the form, the validation functions properly. However, if I extract it into ...

Angular 7's Singleton Service Feature

My service setup looks like this: export abstract class ILoggingService { // abstract functions here } export class LoggingService implements ILoggingService { // service implementation } export class MockLoggingService implements ILoggingServic ...

`AngularFire services/factories that utilize nested models`

I am currently exploring how to nest models using factory-model/classes in combination with Firebase for data storage. For instance, imagine I am developing a task management app where Lists contain multiple Tasks, and each Task has various Details associa ...

What could be causing MongoDB to not delete documents on a 30-second cycle?

Having trouble implementing TTL with Typegoose for MongoDB. I am trying to remove a document from the collection if it exceeds 30 seconds old. @ObjectType("TokenResetPasswordType") @InputType("TokenResetPasswordInput") @index( { cr ...

Determining when to include @types/packagename in React Native's dev dependencies for a specific package

Just getting started with React Native using typescript. Take the package vector icon for example, we need to include 2 dependencies: 1. "react-native-vector-icons": "^7.1.0" (as a dependency) 2. "@types/react-native-vector-icons": "^6.4.6" (as a dev ...

In the realm of React Native, an error arises when attempting to access 'this._nativeModule.isBluetoothEnabled', as the reference to null prevents it from

Recently, I delved into working with react native and attempted to incorporate react-native-bluetooth-classic into my project. The URL for the API overview can be found here. However, I encountered an issue that has me stuck: "TypeError: null is not ...

Tips for efficiently handling large Excel files in NodeJS without freezing the user interface

Currently, my NodeJS/Angular/Electron app is utilizing the ExcelJS library to read large Excel files that contain over 10,000 lines. While smaller files are processed smoothly, larger files take between 3.9 and 5 seconds to load, during which time the CSS ...