由于我无法使用GoogleWebAuthorizationBroker.AuthorizeAsync API捕获浏览器窗口关闭事件,因此我使用此链接(http://www.daimto.com/google-api-and-oath2/)创建了一个嵌入式浏览器并对用户进行了身份验证。我无法继续使用访问令牌上传google drive中的文件。是否有任何示例可以从上面的链接继续从Google Drive上传/下载文件。
你好,阿姆鲁特
发布于 2016-07-26 09:05:39
来自同一个作者,有一个文档如何上传/下载文件到Google Drive。
与大多数Google API一样,您需要进行身份验证才能连接到它们。为此,您必须首先在Google开发人员控制台上注册您的应用程序。在API下,确保启用Google Drive API
和Google Drive SDK
,一如既往,不要忘记在同意屏幕表单上添加产品名称和电子邮件地址。
确保您的项目至少设置为.net 4.0。
添加以下NuGet包
PM> Install-Package Google.Apis.Drive.v2
为了download一个文件,我们需要知道它的文件资源,获取文件id的唯一方法是我们之前使用的Files.List()
命令。
public static Boolean downloadFile(DriveService _service, File _fileResource, string _saveTo)
{
if (!String.IsNullOrEmpty(_fileResource.DownloadUrl))
{
try
{
var x = _service.HttpClient.GetByteArrayAsync(_fileResource.DownloadUrl );
byte[] arrBytes = x.Result;
System.IO.File.WriteAllBytes(_saveTo, arrBytes);
return true;
}
catch (Exception e)
{
Console.WriteLine("An error occurred: " + e.Message);
return false;
}
}
else
{
// The file doesn't have any content stored on Drive.
return false;
}
}
使用_service.HttpClient.GetByteArrayAsync
,我们可以将我们想要下载的文件的下载url传递给它。下载文件后,只需简单地将文件写入磁盘即可。
记住,从创建一个目录开始,为了upload一个文件,你必须能够告诉谷歌它的mime-type
是什么。我这里有一个小方法,试着解决这个问题。只需将文件名发送给它即可。注意:上传文件到Google Drive时,如果文件的名称与已经存在的文件同名。Google Drive只是上传它,那里的文件没有更新你只是得到了两个同名的文件。它只基于fileId
进行检查,而不是基于文件名。如果你想更新一个文件,你需要使用更新命令,我们稍后会检查它。
public static File uploadFile(DriveService _service, string _uploadFile, string _parent) {
if (System.IO.File.Exists(_uploadFile))
{
File body = new File();
body.Title = System.IO.Path.GetFileName(_uploadFile);
body.Description = "File uploaded by Diamto Drive Sample";
body.MimeType = GetMimeType(_uploadFile);
body.Parents = new List() { new ParentReference() { Id = _parent } };
// File's content.
byte[] byteArray = System.IO.File.ReadAllBytes(_uploadFile);
System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
try
{
FilesResource.InsertMediaUpload request = _service.Files.Insert(body, stream, GetMimeType(_uploadFile));
request.Upload();
return request.ResponseBody;
}
catch (Exception e)
{
Console.WriteLine("An error occurred: " + e.Message);
return null;
}
}
else {
Console.WriteLine("File does not exist: " + _uploadFile);
return null;
}
}
https://stackoverflow.com/questions/38560485
复制相似问题