我正在考虑将我的Google Drive连接到我的应用程序,以便我可以将文件上传到其中。
I遵循了文档,并且已经在Google Cloud Portal上设置了我的应用程序,创建了我的OAuth客户端ID和我的服务帐户,以便能够将其连接到我的应用程序。在使用Postman和我的客户ID进行测试时,我可以将文件上传到驱动器,但是文件名没有与我的文件一起发送。在解决问题一段时间以来,我决定继续在应用程序中实施该问题,而是看到甚至在我的Google Drive中上传的文件也不是一个文件。以下是将上传文件的方法:
public async Task DriveUploadBasic(string filePath) {
try {
// Load pre-authorized user credentials from the environment.
string keyPath = $"{Directory.GetCurrentDirectory()}\\googleapi1.json";
GoogleCredential credential = GoogleCredential.FromFile(keyPath)
.CreateScoped(DriveService.Scope.Drive)
.CreateScoped(DriveService.Scope.DriveFile);
// Create Drive API service.
var service = new DriveService(new BaseClientService.Initializer {
HttpClientInitializer = credential,
ApplicationName = "TestingApp1"
});
//service.HttpClient.Timeout = TimeSpan.FromMinutes(2);
// Upload file photo.jpg on drive.
var fileMetadata = new Google.Apis.Drive.v3.Data.File() {
Name = "test1.csv"
};
FilesResource.CreateMediaUpload request;
// Create a new file on drive.
using (var stream = new FileStream(filePath, FileMode.Open)) {
// Create a new file, with metadata and stream.
request = service.Files.Create(fileMetadata, stream, "text/csv");
request.Fields = "id";
var progress = await request.UploadAsync().ConfigureAwait(false);
if (progress.Status == UploadStatus.Failed) {
Log($"Upload failed: {progress.Exception}");
}
var file = request.ResponseBody;
//Log(request.ResponseBody.ToString());
// Prints the uploaded file id.
}
}
catch (Exception e) {
if (e is AggregateException) {
Log("Credential Not found");
}
else if (e is FileNotFoundException) {
Log("File not found");
}
else {
Log(e.Message);
}
}
}
任何帮助很棒,谢谢!
当Debuggin这是我的发现时:
连接是通过服务创建的,没有例外
上传文件正在读取(所有882个字节)