gpt4 book ai didi

firebase - 无法找到使用 REST API 上传到 Google Drive 的文件

转载 作者:行者123 更新时间:2023-12-04 08:42:25 25 4
gpt4 key购买 nike

我正在尝试使用 REST API 和服务帐户将媒体文件上传到 Google Drive。我有一个 Cloud Functions 后端,我在其中使用 Google DRIVE API 的正确范围进行身份验证并将访问 token (如下面的代码段所示)返回给客户端,然后客户端可以向 Google Drive 发出上传请求。

const auth = new google.auth.GoogleAuth({
scopes: [
'https://www.googleapis.com/auth/cloud-platform',
'https://www.googleapis.com/auth/drive.appdata',
'https://www.googleapis.com/auth/drive'
]
});

const client = await auth.getClient();
return await client.getAccessToken();

如所见 here 在网络上运行良好甚至在 expo-snack-web 上看到的 here .现在,我需要让它在移动平台上工作,使用 React Native,但每次上传文件时,我都会收到 200 响应和文件 ID,但我在指定文件夹或任何地方都找不到该文件其他在 Google 云端硬盘上。下面的代码片段只是对我用来上传到网络版本的相同逻辑的重写。
import React, {useEffect, useState} from 'react'
import {View, Text, StyleSheet, Platform, Button, Image} from 'react-native'
import * as ImagePicker from 'expo-image-picker';
import axios from 'axios'
import {decode as atob} from 'base-64'

export const UploadToDrive = (props) => {

const [image, setImage] = useState(null);
const [uploadPercent, setUploadPercent] = useState(0)
const [mimeType, setMimeType] = useState('')

useEffect(() => {
(async () => {
if (Platform.OS !== 'web') {
const { status } = await ImagePicker.requestCameraRollPermissionsAsync();
if (status !== 'granted') {
alert('Sorry, we need camera roll permissions to make this work!');
}
}
})();
}, []);

const pickImage = async () => {
const baseURL = 'https://dummy-server-address/api';

// Simultaneously get the access token while picking the media
const [{response}, result] = await Promise.all([
fetch(
`${baseURL}/services/fetch-access-token`,
{
mode: "cors",
}
)
.then((res) => res.json())
.then((resp) => resp)
.catch((err) => console.log(err)),

ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
aspect: [4, 3],
quality: 1,
})
]).catch((err) => console.log(err))

// ensure that all needed parameters/fields are present
if (!result.cancelled && response.token) {
const accessToken = response.token

const uri = "file:///" + result.uri.split("file:/").join("");
setImage(uri);

const file = result

let filename = uri.split('/').pop();
let match = /\.(\w+)$/.exec(filename);
let type = match ? `image/${match[1]}` : `image`;

file.name = filename;
file.type = type
file.uri = uri
console.log(file)

setMimeType(file.type)
// Upload the image using the fetch and FormData APIs
let formData = new FormData();

const metadata = {
name: file.name,
type: file.type || 'multipart/form-data',
parents: ["1yz6MUU0YfXz0rl7TObq-JOPCmC6sHKdQ"],
};
// construct the file metadata for the upload
formData.append(
"metadata",
new Blob([JSON.stringify(metadata)], { type: "application/json" })
);

// formData.append('file', { uri, name: filename, type });
formData.append('file', file);
const url =
"https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&fields=id";

// let uploadPercent;
const upload_res = await axios(url, {
method: "POST",
headers: {
Authorization: "Bearer " + accessToken,
},
data: formData,
onUploadProgress: (p) => {
setUploadPercent((p.loaded / p.total) * 100)
},
})
.catch(err => console.log({err}))
.finally(() => setUploadPercent(0));

console.log({ data: upload_res.data });

} else {
throw new Error('You do not have all the right variables to make an upload')
}
};

return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>

{!!uploadPercent && <Text style={styles.uploadPercent}>Upload Percent: {`${uploadPercent.toFixed(2)}%`}</Text>}

<Button style={styles.button} title="Pick a file" onPress={pickImage} />
{image && mimeType.includes('image') && <Image source={{ uri: image }} style={{ width: 200, height: 200, marginTop: 20 }} />}
</View>
)
}


const styles = StyleSheet.create({
button: {
position: 'absolute',
top: '10%'
},
uploadPercent: {
color: 'tomato',
fontSize: 15,
fontWeight: 'bold',
marginBottom: 20
}
})
请问,我可能做错了什么?

最佳答案

  • 如果您 upload将服务帐户文件放到不是他的 Drive 时,需要设置参数 supportsAllDrivestrue
  • 或者,使用 domain-wide delegation with impersonation让服务帐户代表您上传文件 - 在这种情况下,您不需要与服务帐户共享您的文件夹。
  • 关于firebase - 无法找到使用 REST API 上传到 Google Drive 的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64493342/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com