Google Drive API 无法从 IIS 上传文件

2024-03-05

我正在使用 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 块内,catch 正在记录异常,但不会引发异常。

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

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

UPDATE

它适用于除 Office 文件之外的所有文件。由于 XLSX 等在 google 驱动器上看起来不正确,我修改了 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); and DriveService.Files.Insert(body, stream, GetMimeType(uploadFile))这样文件就可以正确上传到 Google 驱动器上,她是我的方法 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。

Code

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 驱动器示例项目 https://github.com/LindaLawton/Google-Dotnet-Samples/blob/master/Google-Drive/Google-Drive-Api-dotnet/Google-Drive-Api-dotnet/DaimtoGoogleDriveHelper.cs我刚刚添加了转换。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Google Drive API 无法从 IIS 上传文件 的相关文章

随机推荐