Google Drive API没有从IIS上传文件

本文关键字:IIS 文件 Drive API Google | 更新日期: 2023-09-27 18:04:24

我使用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用户对该文件夹的完全访问权限。

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

它对所有文件都有效,除了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;
    }

Google Drive API没有从IIS上传文件

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

一定要加上

request.Convert = true;

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

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

代码从谷歌驱动器的样本项目,我只是添加了转换。