我正在制作一个链接到 Google 云端硬盘帐户的简单应用程序,然后可以将文件上传到任何目录并使用(直接)下载链接进行响应。 我已经获得了我的用户凭证和 DriveService 对象,但我似乎找不到任何好的示例或文档。在 APIv3 上。
因为我对 OAuth
不是很熟悉,所以我现在要求一个关于如何上传包含 byte[]
内容的文件的清晰明了的解释。
我将应用程序链接到 Google Drive 帐户的代码:(不确定这是否完美)
UserCredential credential;
string dir = Directory.GetCurrentDirectory();
string path = Path.Combine(dir, "credentials.json");
File.WriteAllBytes(path, Properties.Resources.GDJSON);
using(var stream = new FileStream(path, FileMode.Open, FileAccess.Read)) {
string credPath = Path.Combine(dir, "privatecredentials.json");
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
}
// Create Drive API service.
_service = new DriveService(new BaseClientService.Initializer() {
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
File.Delete(path);
到目前为止我的上传代码:(显然不起作用)
public void Upload(string name, byte[] content) {
Google.Apis.Drive.v3.Data.File body = new Google.Apis.Drive.v3.Data.File();
body.Name = name;
body.Description = "My description";
body.MimeType = GetMimeType(name);
body.Parents = new List() { new ParentReference() { Id = _parent } };
System.IO.MemoryStream stream = new System.IO.MemoryStream(content);
try {
FilesResource.InsertMediaUpload request = _service.Files.Insert(body, stream, GetMimeType(_uploadFile));
request.Upload();
return request.ResponseBody;
} catch(Exception) { }
}
谢谢!
最佳答案
启用 Drive API 后,注册您的项目并从 Developer Consol 获取您的凭据。 ,您可以使用以下代码来获得用户的同意并获得经过身份验证的云端硬盘服务
string[] scopes = new string[] { DriveService.Scope.Drive,
DriveService.Scope.DriveFile};
var clientId = "xxxxxx"; // From https://console.developers.google.com
var clientSecret = "xxxxxxx"; // From https://console.developers.google.com
// here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId,
ClientSecret = clientSecret},
scopes,
Environment.UserName,
CancellationToken.None,
new FileDataStore("MyAppsToken")).Result;
//Once consent is recieved, your token will be stored locally on the AppData directory, so that next time you wont be prompted for consent.
DriveService service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "MyAppName",
});
service.HttpClient.Timeout = TimeSpan.FromMinutes(100);
//Long Operations like file uploads might timeout. 100 is just precautionary value, can be set to any reasonable value depending on what you use your service for.
以下是用于上传到云端硬盘的有效代码。
// _service: Valid, authenticated Drive service
// _uploadFile: Full path to the file to upload
// _parent: ID of the parent directory to which the file should be uploaded
public static Google.Apis.Drive.v2.Data.File uploadFile(DriveService _service, string _uploadFile, string _parent, string _descrp = "Uploaded with .NET!")
{
if (System.IO.File.Exists(_uploadFile))
{
File body = new File();
body.Title = System.IO.Path.GetFileName(_uploadFile);
body.Description = _descrp;
body.MimeType = GetMimeType(_uploadFile);
body.Parents = new List<ParentReference>() { new ParentReference() { Id = _parent } };
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)
{
MessageBox.Show(e.Message,"Error Occured");
}
}
else
{
MessageBox.Show("The file does not exist.","404");
}
}
这是确定 MimeType 的小函数:
private static 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;
}
此外,您可以注册 ProgressChanged
事件并获取上传状态。
request.ProgressChanged += UploadProgessEvent;
request.ChunkSize = FilesResource.InsertMediaUpload.MinimumChunkSize; // Minimum ChunkSize allowed by Google is 256*1024 bytes. ie 256KB.
和
private void UploadProgessEvent(Google.Apis.Upload.IUploadProgress obj)
{
label1.Text = ((obj.ByteSent*100)/TotalSize).ToString() + "%";
// do updation stuff
}
上传就差不多了..
Source .
关于C# Google Drive APIv3 上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40049021/