c# - Google Drive API 不从 IIS 上传文件

标签 c# iis google-drive-api google-api-dotnet-client service-accounts

我正在使用 Google API .Net 客户端库通过使用服务帐户的 Google Drive API 上传到 Google Drive。当我从 Visual Studio 尝试(调试)时效果很好,甚至当我在本地 IIS 上部署它时效果很好。

但是当我在我的服务器(Microsoft Server 2012,IIS 8.5)上部署文件时,文件没有上传,也没有抛出任何异常。这是一段代码:

byte[] byteArray = System.IO.File.ReadAllBytes(uploadFile);
Logger.LoggingService.LogError("GoogleHelper", "Is byteArray null  :" + (byteArray == null)); // Line to check if bytearray is null, I am getting false in log.
Logger.LoggingService.LogError("GoogleHelper", "ByteArray length  :" + byteArray.Length); // Getting actual length here.
System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);

FilesResource.InsertMediaUpload request = DriveService.Files.Insert(body, stream, GetMimeType(uploadFile));
request.Upload();
return request.ResponseBody;

我得到 Null 作为返回。上面的代码在 try block 内,catch 正在记录异常,但没有抛出异常。

我已授予 IIS 用户对此文件夹的完全访问权限。

有人遇到过同样的问题吗?欢迎任何指向解决方案的指针。

更新

它适用于除 Office 文件之外的所有文件。由于 XLSX 等在谷歌驱动器上看起来不正确,我修改了 MIME 类型,如下所示:

Google.Apis.Drive.v2.Data.File body = new Google.Apis.Drive.v2.Data.File();                    
body.Title = System.IO.Path.GetFileName(uploadFile);
body.Description = description;
body.MimeType = GetMimeType(uploadFile, false);
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);
FilesResource.InsertMediaUpload request = DriveService.Files.Insert(body, stream, GetMimeType(uploadFile));
request.ResponseReceived += request_ResponseReceived;
request.Upload();
return request.ResponseBody; 

看到我调用了两次 GetMimeType body.MimeType = GetMimeType(uploadFile, false);DriveService.Files.Insert(body, stream, GetMimeType(uploadFile))这样文件就可以正确地上传到谷歌驱动器上,她是我的方法 GetMimeType:

private string GetMimeType(string fileName, bool ignoreExtension = true)
    {
        string mimeType = "application/unknown";
        string ext = System.IO.Path.GetExtension(fileName).ToLower();

        if (ignoreExtension == false)
        {
            switch (ext)
            {
                case ".ppt":
                case ".pptx":
                    mimeType = "application/vnd.google-apps.presentation";
                    break;
                case ".xls":
                case ".xlsx":
                    mimeType = "application/vnd.google-apps.spreadsheet";
                    break;
                case ".doc":
                case ".docx":
                    mimeType = "application/vnd.google-apps.document";
                    break;
                default:
                    Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
                    if (regKey != null && regKey.GetValue("Content Type") != null)
                        mimeType = regKey.GetValue("Content Type").ToString();
                    break;
            }
        }
        else
        {
            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;
    }

最佳答案

我不确定这是否是问题所在。我没有无法对其进行测试的生产 IIS 服务器。我怀疑问题可能出在 mime 类型上,我不确定它在本地系统而不是你的生产系统上是如何工作的,但试试这个代码。如果它不起作用,我可以删除答案。

确保添加

request.Convert = true;

这会告诉驱动器将文件转换为驱动器格式,而不仅仅是上传 xls 等。

代码

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;
        }

        /// <summary>
        /// Uploads a file
        /// Documentation: https://developers.google.com/drive/v2/reference/files/insert
        /// </summary>
        /// <param name="_service">a Valid authenticated DriveService</param>
        /// <param name="_uploadFile">path to the file to upload</param>
        /// <param name="_parent">Collection of parent folders which contain this file. 
        ///                       Setting this field will put the file in all of the provided folders. root folder.</param>
        /// <returns>If upload succeeded returns the File resource of the uploaded file 
        ///          If the upload fails returns null</returns>
        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<ParentReference>() { 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.Convert = true;
                    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;
            }           

        }

Google drive sample project 中提取的代码我刚刚添加了转换。

关于c# - Google Drive API 不从 IIS 上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31580206/

相关文章:

c# - 自动将一些 Where 子句添加到 Linq 表达式树

jquery - IIS 上的 Javascript Ajax URL 映射问题

http - Web API GET 请求中的电子邮件地址

c# - 如何将 tabSpace 插入到字符串中?

c# - 在 .NET 4 中,如何使用 Rx 的 IScheduler.SchedulePeriodic 方法允许取消正在运行的工作

c# - 套接字连接的字符编码问题

.net - 使用 SNI 选项以编程方式在 IIS 8 上添加绑定(bind)

javascript - 谷歌应用脚​​本,团队驱动的谷歌选择器

java - 在 Google 云端硬盘中下载文件时,文件暂时移动错误

android - 使用 Drive SDK 从 Google Drive 下载文件时获取 "302 Moved Temporarily"