当我下载一个在React Native中上传到Google Drive的文件时,我会得到与原始文件不同的文件大小



大家好

我的目标是用Google Drive API V3将我存储在设备存储中的数据库(RealmJS(上传到Google Drive,为此,我已经安装了一些节点模块,如react-native-fs@react-native-community/google-signin

数据库上传过程进行得很顺利,但我不知道实际应该使用什么方法上传文件,我到处都找过了,发现有一个方法Buffernew Blob()new FormData()

我尝试过这三种方法,其中两种Buffernew Blob()产生的文件大小与原始文件不同,new FormData()方法的结果只会导致网络错误,即使我的网络很好

我还是Google Drive API V3的新手,我不知道如何解决这个问题,即使我读了文档,我也听不懂,因为我的英语不好。如果你对这个问题有一个想法,并对你发布的代码进行解释,这将对我和其他读者都有帮助。

这是我的代码

import fs from 'react-native-fs';
import {GoogleSignin} from '@react-native-community/google-signin';
/**
* Here I have logged in to my own Google account so I just need to take the token
*/
async function backupDatabase() {
const {accessToken} = await GoogleSignin.getTokens();
const noneMime = 'application/octet-stream';
/**
* Using "uploadType=resumable" because my file size is larger than 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');
/**
* I read the file, it's ".realm" ext soo i using
* "base64" encode
*/
const myFile = await fs.readFile(myPathFile, 'base64');

/**
* This is how i upload the file with this method
*/
const fileBlob = new Blob([myFile], {type: noneMime});
const fileBuffer = Buffer.from(myFile, 'base64');
/**
* This one is always failing a network failed even
* my network 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',
},
/**
* At this stage, I don't understand what method to use?
* You guys have any idea? Is that "Buffer", "Blob", or "FormData"?
*/
body: fileBlob, // OR "fileBuffer" OR "fileFormData" 
});
const responseUpload = await uploadDatabase.json();
console.log(responseUpload);
}
}

在这个问题中,我在使用API文件时出错。这里的错误是我没有将查询alt=media传递到URL中,它应该是"https://www.googleapis.com/drive/v3/files/" + fileId + "?alt=media"。参见文档

在上面的代码中,我使用fileBuffer而不是fileBlobfileFromData作为request body,仅此而已,我上传的Realm完全正常,我可以正常打开

感谢Kaiido对我的帮助:D

最新更新