我正在构建将文件从我的网络应用程序上传到我的客户端谷歌硬盘的功能。我不希望应用程序对用户进行身份验证。谁曾从我的文件上传任何文件,我希望将其上传到我客户的谷歌硬盘。
我假设服务帐户是用于此目的的一个。我是对的吗?
当我使用以下代码上传文件时,它会成功上传,但在"我的云端硬盘"下无法显示。然后我添加了一个权限,基本上与我的Gmail帐户共享该文件。然后它在"与我共享"部分。
我希望这些文件可以在"我的云端硬盘"部分就像普通文件一样。
任何人都可以指出我在这里做错了吗?
private DriveService GetServiceInstance()
{
try
{
var certificate = new X509Certificate2(Server.MapPath("path to .p12 key"), "notasecret", X509KeyStorageFlags.Exportable);
string[] scopes = new string[] {
DriveService.Scope.Drive,
DriveService.Scope.DriveFile,
DriveService.Scope.DriveAppdata,
DriveService.Scope.DriveMetadata
};
var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer("Client Email")
{
Scopes = scopes
}.FromCertificate(certificate));
// Create the service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Drive API Sample",
});
return service;
}
catch (Exception ex)
{
throw;
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
try
{
if (fu.HasFile)
{
DriveService service = GetServiceInstance();
Google.Apis.Drive.v2.Data.File body = new Google.Apis.Drive.v2.Data.File();
body.Title = fu.FileName;
body.MimeType = fu.PostedFile.ContentType;
FilesResource.InsertMediaUpload request = service.Files.Insert(body, fu.PostedFile.InputStream, fu.PostedFile.ContentType);
request.Upload();
// I want to eliminate this part. where i do not have to give permission. As i want these files to get stored on same google drive account for which i have generated this service account and client keys
Google.Apis.Drive.v2.Data.File file = request.ResponseBody;
Google.Apis.Drive.v2.Data.Permission newPermission = new Google.Apis.Drive.v2.Data.Permission();
newPermission.Value = "my email address";
newPermission.Type = "user";
newPermission.Role = "writer";
Google.Apis.Drive.v2.PermissionsResource.InsertRequest insertRequest = service.Permissions.Insert(newPermission, file.Id);
insertRequest.SendNotificationEmails = false;
insertRequest.Execute();
}
}
catch (Exception ex)
{
throw;
}
}
答案 0 :(得分:0)
不要使用服务帐户。为服务器中的目标帐户嵌入刷新令牌。见How do I authorise an app (web or installed) without user intervention? (canonical ?)
答案 1 :(得分:-1)
我已经创建了一个特定的文件夹并将该文件夹共享到我的电子邮件地址。将文档上载到该文件夹。这解决了我的问题。