When downloading files that I uploaded to Google Drive using React Native, I noticed that the file size is not consistent with the original file

Greetings Everyone!

I am aiming to transfer the database (RealmJS) that is currently stored on my device storage to Google Drive using Google Drive API V3. To accomplish this, I have already installed various node modules such as react-native-fs and

@react-native-community/google-signin
.

The process of uploading the database is progressing smoothly. However, I am encountering difficulty in determining the appropriate method for file upload. After extensive research, I came across methods like Buffer, new Blob(), and new FormData().

Despite trying all three methods, I observed discrepancies in file size with the Buffer and new Blob() options, while the new FormData() method consistently resulted in network errors despite having a stable network connection.

Given my limited experience with Google Drive API V3 and struggles with English comprehension, I am seeking assistance in resolving this issue. Any insights or solutions shared will not only benefit me but also assist other readers facing similar challenges. Please include a clear explanation along with any provided code snippets.

Below is the code snippet I am working with:

import fs from 'react-native-fs';
import {GoogleSignin} from '@react-native-community/google-signin';

/**
 * Logging into my personal Google account to retrieve the access token
 */
async function backupDatabase() {
  const {accessToken} = await GoogleSignin.getTokens();
  const noneMime = 'application/octet-stream';

  /**
   * Using "uploadType=resumable" due to larger file size exceeding 5MB
   */
  const requestUpload = await fetch(
    'https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable',
    {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${accessToken}`,
        'Content-Type': 'application/json; charset=UTF-8',
        'X-Upload-Content-Type': noneMime,
      },
      body: JSON.stringify({
        name: 'mydb.realm',
        mimeType: noneMime,
        description: 'Backup Database',
        parents: ['appDataFolder'],
      }),
    },
  );

  if (requestUpload.ok) {
    const resumableUploadURL = requestUpload.headers.get('location');

    /**
     * Reading the file with ".realm" extension and encoding it in "base64"
     */
    const myFile = await fs.readFile(myPathFile, 'base64');
    
    /**
     * Uploading the file using different methods
     */
    const fileBlob = new Blob([myFile], {type: noneMime});
    const fileBuffer = Buffer.from(myFile, 'base64');
    
    // The following method consistently fails causing network issues even though the connection is fine
    const fileFormData = new FormData();
    fileFormData.append('file', fileBlob);

    const uploadDatabase = await fetch(resumableUploadURL, {
      method: 'PUT',
      headers: {
        Authorization: `Bearer ${accessToken}`,
        'Content-Type': 'application/octet-stream',
        'X-Upload-Content-Type': 'application/octet-stream',
      },

      // Unsure about which method to use - "Buffer", "Blob", or "FormData"?
      body: fileBlob, // OR "fileBuffer" OR "fileFormData" 
    });

    const responseUpload = await uploadDatabase.json();
    console.log(responseUpload);
  }
}

Answer №1

While troubleshooting an issue, I realized my mistake in using the API files.get. The error was that I forgot to include the query alt=media in the URL. The correct format should be

"https://www.googleapis.com/drive/v3/files/" + fileId + "?alt=media"
. You can refer to the documentation here.

In the provided code snippet, I utilized fileBuffer instead of fileBlob or fileFromData as the request body. As a result, the Realm that I uploaded behaved normally and could be accessed without any issues.

A special thanks to Kaiido for their invaluable assistance!

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

Design a hover zone that allows for interaction without disrupting click events

I am looking to create a tooltip box that appears when hovering over an element, and I want the tooltip to only disappear when the user's mouse exits a specific custom hover area outlined by a vector graphic. My current implementation is working, but ...

Is there a way to create a JavaScript-driven search filter that updates automatically?

My website showcases a lineup of League of Legends champion icons, with one example shown below: <div class = "champion"> <p>Aatrox <img class = "face_left" src = "images/small/Aatrox.png"> <div class = "name" onmouseover="if(cha ...

Saving a jimp resized image in a mongoDb database: A step-by-step guide

Does anyone have advice on saving a resized image using Jimp directly to MongoDB database in a Node.js project with Express, Multer, and GridFS? The write method I am currently using only writes to a folder. ...

Is there a glitch in the three.js loadOBJMTL loader?

Encountering an issue with the OBJMTL loader in three.js. I'm working with obj/mtl/jpeg files and getting load errors that look like this: "THREE.OBJMTLLoader: Unhandled line 4033/5601/6659" OBJMTLLoader.js:347 Seems like there is a problem with a c ...

The modal fails to display when the content is positioned below a setInterval function

i have created a notification system using ajax currently, I am attempting to open a modal by clicking on the content of the notification with setInterval the modal works perfectly when the content of my notification is not being updated via setInterval. ...

Dealing with an unspecified parameter can be tricky - here's how you

Currently, I am in the process of developing an angular application. In this project, there is a specific scenario that needs to be handled where a parameter is undefined. Here's a snippet of my code: myImage() { console.log('test') ...

Getting data for Selectize.js

I've implemented Selectize.js to create a tagging feature for assigning users to jobs, utilizing the existing users within the system. In my scenario Following the provided documentation, I have included a select box with the multiple attribute that ...

Having trouble setting up discord.js on my device, getting an error message that says "Unable to install discord.js /

Trying to install Discord.JS by using the command npm install discord.js seems to be successful at first, but unfortunately it doesn't work as expected. Upon running the index.js file, an error message pops up indicating that the module discord.js is ...

Lazy loading Angular component without route - Form control name has no value accessor

Exploring lazyloading a component without routing. I have two components, each with its own formGroup. The parent component, named vehicleForm, includes a FormControl named vehicleDetail. The child component's formGroup includes fields for fuel and ...

Having trouble accessing property '0' of undefined in angular

Below is the code I am currently working on. My goal is to enable editing of the table upon click, but I encountered the error mentioned below. Could someone kindly explain why this is happening and suggest a workaround? <tbody> <tr *ngFor="l ...

Steps for removing a p5.js instance once three.js assets have finished loading

I am trying to implement a preload animation using a p5 sketch while loading a three.js gltf file onto my webpage. The idea is to have the p5 animation play while the heavy gltf file loads in the background. However, I am facing issues with triggering the ...

Retrieving information from JSON files using AngularJS

Here is a JSON object example: [ { "user": "A220", "shorttext": "shanghai", "reportedBy": "S,A", "questions": " [{\"question\":\"Q1\",\"is_mand\":\"0\",\"type\":\"text\",\"a ...

Issue with Ajax form submission functionality not working for sending form data

I recently found the solution to executing a Send Mail script without reloading the page after facing some AJAX issues. However, I am now encountering a problem where the post data is not being received by the PHP script when my form posts to AJAX. For re ...

Utilizing JQuery for a smooth animation effect with the slide down feature

I have a question about my top navigation bar animation. While scrolling down, it seems to be working fine but the animation comes with a fade effect. I would like to achieve a slide-down effect for the background instead. Since scrolling doesn't trig ...

Using the ternary operator to insert elements from one JavaScript array into another array

In my React form, I am dealing with an array of objects that represent different fields. Depending on a boolean state, I need to dynamically change the sequence of fields displayed. While I have no trouble inserting a single object into the array, I am s ...

Encountering a frustrating Npm error while trying to install a package, which persists in throwing

Encountering an error message while trying to run npm install npm ERR! Windows_NT 6.3.9600 npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\ node_modules\&bsol ...

The Art of Div Switching: Unveiling the Strategies

I have a question regarding my website. I have been working on it for some time now, but I have encountered a challenge that I am struggling to overcome. After much consideration, I am unsure of the best approach to take. The issue at hand is that I have ...

How can I set the background of specific text selected from a textarea to a div element?

Is it possible to apply a background color to specific selected text from a Text area and display it within a div? let elem = document.getElementById("askQuestionDescription"); let start = elem.value.substring(0, elem.selectionStart); let selection = ...

Activate Auto Navigation Feature on Mouseover using jQuery

I have a series of divs that cycle automatically to display their contents one after the other every few seconds. The same content is also displayed when the corresponding link is hovered over. The functionality is working correctly, but I would like to ...

Building an easy-to-use jQuery task list

I'm currently working on a basic to-do list in Javascript, but I've encountered an issue. When I check the checkbox, the style of the adjacent text doesn't change as expected. Instead, it's the heading text that is affected by the chang ...