如何在磁盘上没有本地文件的情况下将文件从 Flutter Web 保存到 Google 驱动器?

How to save a file to Google Drive from Flutter web without a local file on disk?

示例 Drive API v3 code 表明,要将文件从您的应用程序保存到 Google 驱动器,您必须先在磁盘上创建一个本地文件,然后再上传它。

因为我使用的是 Flutter for web(以及 Windows 和 Android),所以我无法将文件保存到磁盘。 (我也不想这样做,因为与仅通过 http 在内存中发送字节相比,它非常慢。)

如何将内存中的数据直接发送到 Google 并将其另存为文件(反之亦然)?在我 Googled.

的任何地方,我找不到任何 Dart 代码,也找不到 Drive 示例

我知道你的问题是关于 flutter 的。我不是 flutter 开发者。在评论中与您讨论后,您似乎正在寻找它是否可能。

我用 C# 测试了这个,我可以告诉你这是可能的。您所要做的就是将您的文本转换为内存流,然后上传它而不是文件流。听起来你已经在内存流中有了文本,你应该可以上传它。

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Drive.v3.Data;
using Google.Apis.Services;
using Google.Apis.Upload;

namespace ConsoleApp1
{
    class Program
    {
        static readonly string CredentialsFile = "ServiceAccountCreds.json";
        private static readonly string FileName = "UploadFileString.txt";

        static async Task Main(string[] args)
        {
            Console.WriteLine("Hello World!");


            var serviceAccountCredentials = GoogleCredential.FromFile(CredentialsFile)
                .CreateScoped(DriveService.ScopeConstants.Drive);

            var service = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = serviceAccountCredentials,
                ApplicationName = "Discovery Authentication Sample",
            });

            var uploadString = "Test";
            
            // Upload file Metadata
            var fileMetadata = new Google.Apis.Drive.v3.Data.File()
            {
                Name = FileName,
                Parents = new List<string>() {"1R_QjyKyvET838G6loFSRu27C-3ASMJJa"}
            };

            // Convert raw text to memory stream for upload.
            var fsSource = new MemoryStream(Encoding.UTF8.GetBytes(uploadString ?? ""));

            string uploadedFileId;
            
            // // Create a new file on Google Drive
            // await using (var fsSource = new FileStream(FileName, FileMode.Open, FileAccess.Read))
            // await using (var fsSource = new FileStream(FileName, FileMode.Open, FileAccess.Read))
            // {
                // Create a new file, with metadata and stream.
                var request = service.Files.Create(fileMetadata, fsSource, "text/plain");
                request.Fields = "*";
                var results = await request.UploadAsync(CancellationToken.None);

                if (results.Status == UploadStatus.Failed)
                {
                    Console.WriteLine($"Error uploading file: {results.Exception.Message}");
                }

                // the file id of the new file we created
                uploadedFileId = request.ResponseBody?.Id;
            //}
        }
    }
}

理论上任何 Flutter 样本都应该可以工作。

使用

dependencies:
  google_drive_client: ^1.0.3

import 'dart:io';

import 'package:dio/dio.dart';
import 'package:example/config.dart';
import 'package:flutter/material.dart';
import 'package:google_drive_client/google_drive_client.dart';
import 'package:path_provider/path_provider.dart';

void main() {
  runApp(App());
}

class App extends StatelessWidget {
  final GoogleDriveClient client = GoogleDriveClient(Dio(), getAccessToken: () async => Config.ACCESS_TOKEN);
  final String id = '';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: ListView(
          children: [
            FlatButton(
              child: Text('list'),
              onPressed: () async {
                print(await client.list());
              },
            ),
            FlatButton(
              child: Text('create'),
              onPressed: () async {
                final File file = File((await getTemporaryDirectory()).path + '/testing2');
                file.writeAsStringSync("contents");
                var meta = GoogleDriveFileUploadMetaData(name: 'testing');
                print(await client.create(meta, file));
              },
            ),
            FlatButton(
              child: Text('delete'),
              onPressed: () async {
                await client.delete(id);
              },
            ),
            FlatButton(
              child: Text('download'),
              onPressed: () async {
                await client.download(id, 'testing');
              },
            ),
            FlatButton(
              child: Text('get'),
              onPressed: () async {
                print(await client.get(id));
              },
            ),
          ],
        ),
      ),
    );
  }
}