由于我无法使用GoogleWebAuthorizationBroker.AuthorizeAsync API捕获浏览器窗口关闭事件,因此我沿着此链接(http://www.daimto.com/google-api-and-oath2/)创建嵌入式浏览器并对用户进行身份验证。我无法继续使用访问令牌在谷歌驱动器上传文件。是否有任何示例可以从上述链接继续从Google云端硬盘上传/下载文件。使用嵌入式浏览器将文件上传到Google Drive#
问候, Amrut
由于我无法使用GoogleWebAuthorizationBroker.AuthorizeAsync API捕获浏览器窗口关闭事件,因此我沿着此链接(http://www.daimto.com/google-api-and-oath2/)创建嵌入式浏览器并对用户进行身份验证。我无法继续使用访问令牌在谷歌驱动器上传文件。是否有任何示例可以从上述链接继续从Google云端硬盘上传/下载文件。使用嵌入式浏览器将文件上传到Google Drive#
问候, Amrut
来自同一作者,有一个文件如何上传/下载文件到谷歌驱动器。
与大多数Google API一样,您需要通过身份验证才能连接到它们。为此,您必须先在Google Developer Console上注册您的应用程序。在API下,一定要启用Google Drive API
和Google Drive SDK
,因为一定不要忘记在同意屏幕上添加产品名称和电子邮件地址。
确保您的项目至少设置为.net 4.0。
添加以下NuGet包
PM> Install-Package Google.Apis.Drive.v2
为了download我们需要知道它的文件resorce得到的文件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云端硬盘只是上传它,那里的文件没有更新,您最终只能看到两个同名的文件。它只根据不基于文件名的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;
}
}
我曾经使用过此教程走了,但这里的问题是通过调用API AuthorizeAsync创建本教程DriveService对象用于上传/下载文件。但是我只有访问令牌(http://www.daimto.com/google-api-and-oath2/)。我怎样才能继续进一步上传/下载只有访问令牌是我的问题? – user2734779