谷歌云端硬盘。刷新授权令牌当文件上传 [英] Google Drive. Refresh authorization token while a file is uploading

查看:231
本文介绍了谷歌云端硬盘。刷新授权令牌当文件上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是刷新授权令牌,而一个大的文件被上传到谷歌驱动的方式吗?
为例:目前授权令牌的到期时间是06:00。该文件上传开始在上午05点15分。因此,在06:00的应用程序中获取例外,由于授权令牌是无效的。



我试图与周围的下面源代码的问题,但它确实。不行

  ///<总结> 
///与上载到指定的路径的文件。
///< /总结>
///< PARAM NAME =startFolder方式>的启动文件夹< /参数>
///< PARAM NAME =路径>目标文件的路径< /参数>
///< PARAM NAME =LOCALFILE>将本地文件上传< /参数>
///<返回>将上传的文件< /回报>
私人文件GdUploadFile(文件startFolder,路径字符串,FileInfo的LOCALFILE)
{
如果(startFolder == NULL)
{
抛出新的ArgumentNullException(startFolder) ;
}

如果(LOCALFILE == NULL)
{
抛出新的ArgumentNullException(LOCALFILE); (!localFile.Exists)
}

如果
{
抛出新FileNotFoundException异常(找不到文件,localFile.FullName);
}

无功配置= GetConfiguration();

如果(config.TraceLog)
{
Destination.Logger.LogDebug(的String.Format({0} \tUpload文件\{1} \到\{2} \,Destination.Name,localFile.FullName,路径));
}

串pathToFile = string.IsNullOrEmpty(路径)? localFile.Name:路径;

串remotePath = ExtractFilePath(pathToFile);
VAR fileFolder = GdCreateFolderByPath(startFolder,remotePath);
变种文件名= ExtractFileName(pathToFile);

DriveService服务= GetDriveService();

变种体=新的文件
{
标题=文件名,
说明=我的文件,
的MimeType = BackupFileMimeType,
类= DriveFileKindType,
OriginalFilename =文件名,
FileExtension = localFile.Extension,
=父母新的List< ParentReference>
{
新ParentReference
{
ETag的= fileFolder.ETag,
n = fileFolder.Id,
类= fileFolder.Kind
}
}
};

FilesResource.InsertMediaUpload请求;
无功源=新MediaFileSource(localFile.FullName,BackupFileMimeType);使用

(VAR FILESTREAM = source.GetDataStream())
{
如果(config.TraceLog)
{
Destination.Logger.LogDebug(串.Format({0} \tUploading \{1} \...,Destination.Name,localFile.FullName));
}

=请求service.Files.Insert(身体,FILESTREAM,body.MimeType);

如果(config.TraceLog)
{
INT postedPercent = 0;

request.ProgressChanged + = P =>
{
VAR currentPercent =(INT)(p.BytesSent /(双)source.ContentLength * 100);

如果(currentPercent!= postedPercent)
{
弦乐味精=的String.Format({0} \tPosted {1}%({2}字节), Destination.Name,
currentPercent,p.BytesSent);
Destination.Logger.LogDebug(MSG);
postedPercent = currentPercent;
}
};
}

VAR连接= Destination.Connection为GoogleDriveDestinationConnection;
Debug.Assert的(连接= NULL,连接!= NULL!);

request.ProgressChanged + = P =>
{
布尔refreshAuth = connection.ForceRefreshAuthorization();
变种AUTH =
request.Authenticator为
Google.Apis.Authentication.OAuth2.OAuth2Authenticator< NativeApplicationClient取代;

如果(AUTH = NULL&放大器;!&安培; auth.State = NULL&放大器;!&安培; refreshAuth)
{
VAR状态= connection.AuthorizationState;
auth.State.AccessToken = state.AccessToken;
auth.State.AccessTokenExpirationUtc = state.AccessTokenExpirationUtc;
auth.State.AccessTokenIssueDateUtc = state.AccessTokenIssueDateUtc;
auth.State.Callback = state.Callback;
auth.State.RefreshToken = state.RefreshToken;
auth.State.SaveChanges();

如果(config.TraceLog)
{
Destination.Logger.LogDebug(授权状态上载请求被更新);
}

}
};

request.ChunkSize = CHUNKSIZE;
request.Upload();

如果(config.TraceLog)
{
Destination.Logger.LogDebug(的String.Format({0} \t\{1} \上传Destination.Name,localFile.FullName));
}
}

返回request.ResponseBody;
}


解决方案

考虑做可恢复上传(< A HREF =https://developers.google.com/drive/manage-uploads#resumable相对=nofollow> https://developers.google.com/drive/manage-uploads#resumable ) 。在需要的时候刷新令牌,然后继续你离开的地方上传


What is the way to refresh authorization token while a large file is uploading to Google Drive? For example: expiration time of the current authorization token is "06:00 AM". The file uploading started at "05:15 AM". So at "06:00 AM" the application get exception due authorization token is invalid.

I've tried to around the issue with the below source code, but it does not work.

/// <summary>
/// Uploads a file with a specified path.
/// </summary>
/// <param name="startFolder">The start folder.</param>
/// <param name="path">The path of destination file.</param>
/// <param name="localFile">The local file to upload.</param>
/// <returns>The uploaded file.</returns>
private File GdUploadFile(File startFolder, string path, FileInfo localFile)
{
    if (startFolder == null)
    {
        throw new ArgumentNullException("startFolder");
    }

    if (localFile == null)
    {
        throw new ArgumentNullException("localFile");
    }

    if (!localFile.Exists)
    {
        throw new FileNotFoundException("File not found", localFile.FullName);
    }

    var config = GetConfiguration();

    if (config.TraceLog)
    {
        Destination.Logger.LogDebug(string.Format("{0} \tUpload file \"{1}\" to \"{2}\"", Destination.Name, localFile.FullName, path));
    }

    string pathToFile = string.IsNullOrEmpty(path) ? localFile.Name : path;

    string remotePath = ExtractFilePath(pathToFile);
    var fileFolder = GdCreateFolderByPath(startFolder, remotePath);
    var fileName = ExtractFileName(pathToFile);

    DriveService service = GetDriveService();

    var body = new File
                   {
                       Title = fileName,
                       Description = "My File",
                       MimeType = BackupFileMimeType,
                       Kind = DriveFileKindType,
                       OriginalFilename = fileName,
                       FileExtension = localFile.Extension,
                       Parents = new List<ParentReference>
                                     {
                                         new ParentReference
                                             {
                                                 ETag = fileFolder.ETag,
                                                 Id = fileFolder.Id,
                                                 Kind = fileFolder.Kind
                                             }
                                     }
                   };

    FilesResource.InsertMediaUpload request;
    var source = new MediaFileSource(localFile.FullName, BackupFileMimeType);

    using (var fileStream = source.GetDataStream())
    {
        if (config.TraceLog)
        {
            Destination.Logger.LogDebug(string.Format("{0} \tUploading \"{1}\"...", Destination.Name, localFile.FullName));
        }

        request = service.Files.Insert(body, fileStream, body.MimeType);

        if (config.TraceLog)
        {
            int postedPercent = 0;

            request.ProgressChanged += p =>
                                           {
                                               var currentPercent = (int) (p.BytesSent/(double) source.ContentLength*100);

                                               if (currentPercent != postedPercent)
                                               {
                                                   string msg = string.Format("{0} \tPosted {1}% ({2} bytes)", Destination.Name,
                                                                              currentPercent, p.BytesSent);
                                                   Destination.Logger.LogDebug(msg);
                                                   postedPercent = currentPercent;
                                               }
                                           };
        }

        var connection = Destination.Connection as GoogleDriveDestinationConnection;
        Debug.Assert(connection != null, "connection != null");

        request.ProgressChanged += p =>
                                       {
                                           bool refreshAuth = connection.ForceRefreshAuthorization();
                                           var auth =
                                               request.Authenticator as
                                               Google.Apis.Authentication.OAuth2.OAuth2Authenticator<NativeApplicationClient>;

                                           if (auth != null && auth.State != null && refreshAuth)
                                           {
                                               var state = connection.AuthorizationState;
                                               auth.State.AccessToken = state.AccessToken;
                                               auth.State.AccessTokenExpirationUtc = state.AccessTokenExpirationUtc;
                                               auth.State.AccessTokenIssueDateUtc = state.AccessTokenIssueDateUtc;
                                               auth.State.Callback = state.Callback;
                                               auth.State.RefreshToken = state.RefreshToken;
                                               auth.State.SaveChanges();

                                               if (config.TraceLog)
                                               {
                                                   Destination.Logger.LogDebug("Authorization state for the upload request is updated");
                                               }

                                           }
                                       };

        request.ChunkSize = ChunkSize;
        request.Upload();

        if (config.TraceLog)
        {
            Destination.Logger.LogDebug(string.Format("{0} \t\"{1}\" uploaded", Destination.Name, localFile.FullName));
        }
    }

    return request.ResponseBody;
}

解决方案

Consider doing Resumable upload (https://developers.google.com/drive/manage-uploads#resumable). Refresh the token when needed and continue the upload where you left off.

这篇关于谷歌云端硬盘。刷新授权令牌当文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆