我正在使用.NET SDK for google drive。 我已成功设法在google驱动器上传文件,但是当我使用浏览器登录时无法看到该文件?
这是我的代码:
private string privKey = "-----BEGIN PRIVATE KEY-----\MYKEYHERE-----END PRIVATE KEY-----\n";
private string[] scopes = { DriveService.Scope.Drive };
string serviceAccountEmail = "<myaccounthere>";
public File uploadToDrive(string uploadFilePath)
{
ServiceAccountCredential credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = scopes
}.FromPrivateKey(privKey));
BaseClientService.Initializer initializer = new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
};
// Create Drive API service.
var service = new DriveService(initializer);
if (!string.IsNullOrEmpty(uploadFilePath))
{
File fileMetadata = new File();
fileMetadata.Name = System.IO.Path.GetFileName(uploadFilePath);
fileMetadata.MimeType = GetMimeType(uploadFilePath);
try
{
System.IO.FileStream uploadStream = new System.IO.FileStream(uploadFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
FilesResource.CreateMediaUpload request = service.Files.Create(fileMetadata, uploadStream, GetMimeType(uploadFilePath));
request.ProgressChanged += Upload_ProgressChanged;
request.ResponseReceived += UploadRequest_ResponseReceived;
var task = request.UploadAsync();
task.ContinueWith(t =>
{
});
return request.ResponseBody;
}
catch (System.IO.IOException iox)
{
return null;
}
catch (Exception e)
{
//Log
return null;
}
}
else
{
//Log file does not exist
return null;
}
}
private string GetMimeType(string fileName)
{
string mimeType = "application/unknown";
string ext = System.IO.Path.GetExtension(fileName).ToLower();
Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
if (regKey != null && regKey.GetValue("Content Type") != null)
mimeType = regKey.GetValue("Content Type").ToString();
return mimeType;
}
private void Upload_ProgressChanged(IUploadProgress progress)
{
Debug.WriteLine(progress.Status + " " + progress.BytesSent);
}
private void UploadRequest_ResponseReceived(Google.Apis.Drive.v3.Data.File file)
{
Debug.WriteLine(file.Name + " was uploaded successfully");
}
有没有人碰巧知道我做错了什么?
提前致谢
答案 0 :(得分:0)
如果这不起作用,您可以在此related SO question中尝试建议的答案:
由于您使用的是服务帐户,因此将在此服务帐户的驱动器中创建所有文件夹和文件,这些文件夹和文件无法通过Web UI访问,并且将仅限于默认配额。
要在用户的云端硬盘中添加内容,您需要通过常规OAuth 2.0流程来检索此用户的凭据。您可以在此页面上找到有关OAuth 2.0的更多信息:
希望这有帮助!
答案 1 :(得分:0)
是的,你是对的。服务帐户具有此限制。对于任何有同样问题的人,我所做的(使用.NET)来解决这个问题就是启用域范围授权并模拟我需要的帐户。
例如我的服务帐户是srv1@myaccount.gserviceaccount.com impersonates srv1@gmail.com
ServiceAccountCredential credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer("srv1@myaccount.gserviceaccount.com")
{
Scopes = new string[] { DriveService.Scope.Drive },
User = "srv1@gmail.com"
}.FromPrivateKey(PRIVATE_KEY));
当我使用srv1@gmail.com登录谷歌驱动器时,我现在可以看到文件