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

When attempting to navigate using router.navigate in Angular 6 from a different component, it triggers a refresh

My routing setup is structured as follows: Main App-routing module const routes: Routes = [ { path: '', redirectTo: environment.devRedirect, pathMatch: 'full', canActivate: [AuthenticationGuard] }, { path: &a ...

Issue with Angular 17 button click functionality not functioning as expected

Having trouble with a button that should trigger the function fun(). Here's the code snippet I'm using. In my TS file: fun(): void { this.test = 'You are my hero!'; alert('hello') } Here is the respective HTML: &l ...

The type 'number' cannot be assigned to the type 'Element'

Currently, I am developing a custom hook called useArray in React with TypeScript. This hook handles array methods such as push, update, remove, etc. It works perfectly fine in JavaScript, but encounters errors in TypeScript. Below is the snippet of code f ...

How can I prevent right-clicking with Ctrl+LeftMouseClick in Firefox on MacOS?

I'm looking to implement a shortcut using Ctrl+LeftMouseClick in my React project. It functions perfectly on Chrome on my Mac, but in Firefox the shortcut initiates a right mouse click (event.button = 2). I believe this may be due to MacOS's Rig ...

Dealing with GraphQL mutation errors without relying on the Apollo onError() function

When managing access to an API call server-side, I am throwing a 403 Forbidden error. While trying to catch the GraphQL error for a mutation, I experimented with various methods. (Method #1 successfully catches errors for useQuery()) const [m, { error }] ...

Definition of Promise resolve type in Visual Code's d.ts file

Need help with: // api.js export function getLayout(){ return axios.get('/api/layout').then(res => res.data) } // api.d.ts declare interface JSONResponse { meta: object, data: Array<Field> } export declare function getLayout ...

Passing data between two React components

I'm encountering an issue in my Table.jsx file where I'm attempting to pass the selectedRows Id variable to my Edit.jsx file. This is so that when I open the edit modal, the input fields are pre-populated with the data from the selected row. Tab ...

Tips for successfully mocking axios.get in Jest and passing AxiosPromise type value

I attempted to simulate the axios.get() function using the code below, however TypeScript is returning an error stating "argument of type '{ data: expectedResult }' is not assignable to parameter of type 'AxiosPromise<{}>'". Can any ...

Tips for successfully passing store state as a prop in React-Redux with TypeScript

Having trouble passing information from the initial state of the store to a component where it's supposed to be rendered. Despite a console.log in the component showing that it's undefined, there doesn't seem to be any issue with the initial ...

What Causes a Mongoose Query to Result in an Empty Array?

Hello, I have reviewed similar questions regarding the issue I am facing with developing an API. Despite trying different solutions, none seem to resolve my problem. When handling request and response payloads in my API, everything seems to be working fin ...

Incorporating an Angular 2 Directive within the body tag of an

My goal is to create a custom directive that can dynamically add or remove a class from the body element in HTML. The directive needs to be controlled by a service, as I want to manage the visibility of the class from various components. Question: How ca ...

Alternative for using useRouteMatch to retrieve parameters

I'm currently refactoring this code and struggling to find a suitable replacement for this section. This is due to the react-router-dom v6 no longer having the useRouteMatch feature, which I relied on to extract parameters from the URL: import React, ...

"Unindexing data in Angular: A step-by-step guide

Can someone help me figure out how to delete an item by index in Angular? I have a parameter and a remove button, but when I tried putting my parameter inside the remove button it didn't work. How can I fix this? deleteRowFiles(rowIndex: number){ th ...

Guide on saving a PDF file after receiving a binary response using axios

Is there a way to save a PDF file from a binary response received through an axios get request? When making the request, I include the following headers: const config: AxiosRequestConfig = { headers: { Accept: 'application/pdf', respon ...

Using TypeScript: Union Types for Enum Key Values

Here's the code in the TS playground too, click here. Get the Enum key values as union types (for function parameter) I have managed to achieve this with the animals object by using key in to extract the key as the enum ANIMALS value. However, I am s ...

User interface designed for objects containing multiple keys of the same data type along with a distinct key

I have a question that relates to this topic: TypeScript: How to create an interface for an object with many keys of the same type and values of the same type?. My goal is to define an interface for an object that can have multiple optional keys, all of t ...

The presence of v-if does not depend on the model value to toggle the element

I have a scenario where I want to hide the dropdown menu for US states if a different country other than the US is selected. The code snippet I am using to achieve this functionality is shown below: <b-row v-for="demo in demographics" :key=&qu ...

Exploring the power of Typescript and Map in Node.js applications

I am feeling a little perplexed about implementing Map in my nodejs project. In order to utilize Map, I need to change the compile target to ES6. However, doing so results in outputted js files that contain ES6 imports which causes issues with node. Is t ...

What are the steps to create an Angular 8 application with a node backend and deploy it on Firebase?

My goal is to create a web scraper using node and then transfer that data to my angular front end. I am interested in hosting this Progressive Web App on firebase because of its user-friendly interface and cost-effectiveness. This will be my first attempt ...

Clearing the filename in a file type input field using React

When using this input field, only video files are accepted. If any other types of files are uploaded by enabling the "all files" option, an alert will be displayed. While this functionality is working correctly, a problem arises if a non-video file is adde ...