【问题标题】:Dart, Flutter: upload .jpg file to Google DriveDart,Flutter:将 .jpg 文件上传到 Google Drive
【发布时间】:2023-03-31 07:40:01
【问题描述】:

我正在尝试将在我的应用程序中拍摄的一些照片上传到 Google Drive。

我创建了一个项目和一个服务帐户密钥,并启用了 Google Drive API。

我的代码 sn-p 如下所示:

// sfilePath = "/storage/emulated/0/Xyz";
// sfileName = "PIC_17";

final accountCredentials = new ServiceAccountCredentials.fromJson({
"private_key_id": "...",
"private_key": "-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n",
"client_email": "...@...gserviceaccount.com",
"client_id": "...apps.googleusercontent.com",
"type": "service_account"

});

AuthClient client = await clientViaServiceAccount(
  accountCredentials,
  ['https://www.googleapis.com/auth/drive']);

var driveApi = ga.DriveApi(client);

var fileToUpload = File(sfilePath + sfileName + '.jpg');

var response = await driveApi.files.create(ga.File()..name = 'my_file.jpg',
     uploadMedia: ga.Media(fileToUpload.openRead(), fileToUpload.lengthSync()));

print(response.toJson());  

运行程序后

print(response.toJson())

结果:

{id: ..., kind: drive#file, mimeType: image/jpeg, name: my_file.jpg} 

我看到 Dashboard 上 Google Drive API 的请求数在一段时间后增加,但我在我的 Google Drive 上找不到 my_file.jpg。

可能是什么问题?我如何测试会发生什么,确切的响应是什么?

我的解决方案来自:Dart: upload .jpg file to google Drive

谢谢, 莫泽斯

【问题讨论】:

    标签: dart upload


    【解决方案1】:

    我认为问题在于您使用的是服务帐户。 使用服务帐户密钥时,API 正在工作,但您的文件未存储在您的 Google Drive 中,而是存储在单独的 Google Drive 中。 要检查这一点,您可以添加以下代码

    var fileList = await driveApi.files.list();
    fileList.files.forEach((file) => print('---${file.name})'));
    

    使用服务帐户密钥,您将只有一个名为“welcome..”的文件。

    解决方案是使用带有 Google API 密钥的 Firebase 身份验证,代码如下:

    final FirebaseAuth _auth = FirebaseAuth.instance;
    final GoogleSignIn googleSignIn = GoogleSignIn(
    scopes: ['https://www.googleapis.com/auth/drive'],
    );
    
    final GoogleSignInAccount googleSignInAccount = await 
    googleSignIn.signIn();
    final GoogleSignInAuthentication googleSignInAuthentication =
      await googleSignInAccount.authentication;
    
    
    final AuthCredential credential = GoogleAuthProvider.getCredential(
    accessToken: googleSignInAuthentication.accessToken,
    idToken: googleSignInAuthentication.idToken,
    );
    
    AuthResult authResult = await _auth.signInWithCredential(credential);
    
    
    var client = GoogleHttpClient(await googleSignInAccount.authHeaders);
    
    var driveApi = drive.DriveApi(client);
    

    GoogleHttpClient 的定义如下https://stackoverflow.com/a/48485898/8676527

    【讨论】:

      【解决方案2】:

      您必须与凭据的client_email共享您上传图像的驱动器文件夹

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-03-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多