例子Drive API v3 code表明要将文件从您的应用程序保存到 Google 云端硬盘,您必须先在磁盘上创建一个本地文件,然后再上传。
由于我使用 Flutter for web(以及 Windows 和 Android),我无法将文件保存到磁盘。 (我也不想这样做,因为与仅通过 http 在内存中发送字节相比,它非常慢。)
我如何才能将内存中的数据直接发送到 Google 并将其另存为文件(反之亦然)?在我用 Google 搜索过的任何地方,我都找不到这方面的任何 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 样本都应该有效。
关于flutter - 如何在磁盘上没有本地文件的情况下将文件从 Flutter Web 保存到 Google Drive?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70332485/