当前位置: 首页 > 知识库问答 >
问题:

使用Google drive API转移上传文件的所有权

曹泉
2023-03-14

-编辑2-

public bool UploadReportToGoogleDrive(Model model, byte[] ReportPDF_ByteArray, string ddlAddFilesFolder = "root", bool doNotify = true)
    {
        bool isErrorOccured = false;

        try
        {
            SingletonLogger.Instance.Info("UploadReportToGoogleDrive - start");
            FileList fileList = new FileList();
            Google.Apis.Drive.v2.Data.File uploadedFile = new Google.Apis.Drive.v2.Data.File();
            Permission writerPermission = new Permission();

            string accessToken = GetAccessToken();
            #region FIND  REPORT FOLDER
            string url = "https://www.googleapis.com/drive/v2/files?"
                + "access_token=" + accessToken
                + "&q=" + HttpUtility.UrlEncode("title='My Reports' and trashed=false and mimeType in 'application/vnd.google-apps.folder'")
                ;

            // Create POST data and convert it to a byte array.
            List<string> _postData = new List<string>();
            string postData = string.Join("", _postData.ToArray());

            try
            {
                WebRequest request = WebRequest.Create(url);
                string responseString = GDriveHelper.GetResponse(request);
                fileList = JsonConvert.DeserializeObject<FileList>(responseString);
                SingletonLogger.Instance.Info("UploadReportToGoogleDrive - folder search success");
            }
            catch (Exception ex)
            {
                SingletonLogger.Instance.Error("UploadReportToGoogleDrive\\FIND  REPORT FOLDER", ex);
                isErrorOccured = true;
            }
            #endregion FIND  REPORT FOLDER

            if (fileList.Items.Count == 0)
            {
                #region CREATE  REPORT FOLDER
                url = "https://www.googleapis.com/drive/v2/files?" + "access_token=" + accessToken;

                // Create POST data and convert it to a byte array.
                _postData = new List<string>();
                _postData.Add("{");
                _postData.Add("\"title\": \"" + "My Reports" + "\",");
                _postData.Add("\"description\": \"Uploaded with Google Drive API\",");
                _postData.Add("\"parents\": [{\"id\":\"" + "root" + "\"}],");
                _postData.Add("\"mimeType\": \"" + "application/vnd.google-apps.folder" + "\"");
                _postData.Add("}");
                postData = string.Join("", _postData.ToArray());

                try
                {
                    WebRequest request = WebRequest.Create(url);

                    byte[] byteArray = Encoding.UTF8.GetBytes(postData);
                    // Set the ContentType property of the WebRequest.
                    request.ContentType = "application/json";
                    // Set the ContentLength property of the WebRequest.
                    request.ContentLength = postData.Length;//byteArray.Length;
                    // Set the Method property of the request to POST.
                    request.Method = "POST";
                    // Get the request stream.
                    Stream dataStream = request.GetRequestStream();
                    // Write the data to the request stream.
                    dataStream.Write(byteArray, 0, byteArray.Length);
                    // Close the Stream object.
                    dataStream.Close();

                    string responseString = GDriveHelper.GetResponse(request);
                    Google.Apis.Drive.v2.Data.File ReportFolder = JsonConvert.DeserializeObject<Google.Apis.Drive.v2.Data.File>(responseString);
                    ;
                    ddlAddFilesFolder = ReportFolder.Id;
                    SingletonLogger.Instance.Info("UploadReportToGoogleDrive - folder creation success");
                }
                catch (Exception ex)
                {
                    SingletonLogger.Instance.Error("UploadReportToGoogleDrive\\CREATE  REPORT FOLDER", ex);
                    isErrorOccured = true;
                }
                #endregion CREATE  REPORT FOLDER
            }
            else
            {
                ddlAddFilesFolder = fileList.Items.FirstOrDefault().Id;
            }

            if (!isErrorOccured)
            {
                #region UPLOAD NEW FILE - STACKOVER FLOW
                //Createing the MetaData to send
                _postData = new List<string>();

                _postData.Add("{");
                _postData.Add("\"title\": \"" + "Report_" + model.id + "\",");
                _postData.Add("\"description\": \"" + " report of person - " + (model.borrowerDetails.firstName + " " + model.borrowerDetails.lastName) + "\",");

                _postData.Add("\"parents\": [{\"id\":\"" + ddlAddFilesFolder + "\"}],");
                _postData.Add("\"extension\": \"" + "pdf" + "\",");
                _postData.Add("\"appDataContents\": \"" + true + "\",");
                _postData.Add("\"mimeType\": \"" + GDriveHelper.GetMimeType("Report.pdf").ToString() + "\"");
                _postData.Add("}");

                postData = string.Join(" ", _postData.ToArray());
                byte[] MetaDataByteArray = Encoding.UTF8.GetBytes(postData);

                //// creating the Data For the file
                //MemoryStream target = new MemoryStream();
                //myFile.InputStream.Position = 0;
                //myFile.InputStream.CopyTo(target);
                //byte[] FileByteArray = target.ToArray();

                string boundry = "foo_bar_baz";
                url = "https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart" + "&access_token=" + accessToken;

                WebRequest request = WebRequest.Create(url);
                request.Method = "POST";
                request.ContentType = "multipart/related; boundary=\"" + boundry + "\"";

                // Wrighting Meta Data
                string headerJson = string.Format("--{0}\r\nContent-Type: {1}\r\n\r\n",
                                boundry,
                                "application/json; charset=UTF-8");
                string headerFile = string.Format("\r\n--{0}\r\nContent-Type: {1}\r\n\r\n",
                                boundry,
                                GDriveHelper.GetMimeType("Report.pdf").ToString());

                string footer = "\r\n--" + boundry + "--\r\n";

                int headerLenght = headerJson.Length + headerFile.Length + footer.Length;
                request.ContentLength = MetaDataByteArray.Length + ReportPDF_ByteArray.Length + headerLenght;
                Stream dataStream = request.GetRequestStream();
                dataStream.Write(Encoding.UTF8.GetBytes(headerJson), 0, Encoding.UTF8.GetByteCount(headerJson));   // write the MetaData ContentType
                dataStream.Write(MetaDataByteArray, 0, MetaDataByteArray.Length);                                          // write the MetaData


                dataStream.Write(Encoding.UTF8.GetBytes(headerFile), 0, Encoding.UTF8.GetByteCount(headerFile));   // write the File ContentType
                dataStream.Write(ReportPDF_ByteArray, 0, ReportPDF_ByteArray.Length);                                  // write the file

                // Add the end of the request.  Start with a newline

                dataStream.Write(Encoding.UTF8.GetBytes(footer), 0, Encoding.UTF8.GetByteCount(footer));
                dataStream.Close();

                try
                {
                    WebResponse response = request.GetResponse();
                    // Get the stream containing content returned by the server.
                    dataStream = response.GetResponseStream();
                    // Open the stream using a StreamReader for easy access.
                    StreamReader reader = new StreamReader(dataStream);
                    // Read the content.
                    string responseFromServer = reader.ReadToEnd();
                    // Display the content.
                    //Console.WriteLine(responseFromServer);
                    uploadedFile = JsonConvert.DeserializeObject<Google.Apis.Drive.v2.Data.File>(responseFromServer);

                    // Clean up the streams.
                    reader.Close();
                    dataStream.Close();
                    response.Close();

                    SingletonLogger.Instance.Info("UploadReportToGoogleDrive - upload to folder success");
                }
                catch (Exception ex)
                {
                    SingletonLogger.Instance.Error("UploadReportToGoogleDrive\\CREATE REPORT FOLDER", ex);
                    isErrorOccured = true;
                    //return "Exception uploading file: uploading file." + ex.Message;
                }
                #endregion UPLOAD NEW FILE - STACKOVER FLOW
            }

            if (!isErrorOccured)
            {
                #region MAKE ADMIN ACCOUNT OWNER OF UPLOADED FILE - COMMENTED
                url = "https://www.googleapis.com/drive/v2/files/" + uploadedFile.Id
                    + "/permissions/"
                    + uploadedFile.Owners[0].PermissionId
                    + "?access_token=" + accessToken
                    + "&sendNotificationEmails=" + (doNotify ? "true" : "false")
                    ;

                WebRequest request = WebRequest.Create(url);

                string role = "owner", type = "user", value = "aniketpatil87@gmail.com";

                // Create POST data and convert it to a byte array.
                postData = "{"
                + "\"role\":\"" + role + "\""
                + ",\"type\": \"" + type + "\""
                + ",\"value\": \"" + value + "\""
                + ",\"permissionId\":\"" + uploadedFile.Owners[0].PermissionId + "\""
                + ",\"transferOwnership\": \"" + "true" + "\""
                + "}";

                byte[] byteArray = Encoding.UTF8.GetBytes(postData);
                // Set the ContentType property of the WebRequest.
                request.ContentType = "application/json";
                // Set the ContentLength property of the WebRequest.
                request.ContentLength = postData.Length;//byteArray.Length;
                // Set the Method property of the request to POST.
                request.Method = "POST";
                // Get the request stream.
                Stream dataStream = request.GetRequestStream();
                // Write the data to the request stream.
                dataStream.Write(byteArray, 0, byteArray.Length);
                // Close the Stream object.
                dataStream.Close();

                //TRY CATCH - IF TOKEN IS INVALID
                try
                {
                    string responseString = GDriveHelper.GetResponse(request);
                    SingletonLogger.Instance.Info("UploadReportToGoogleDrive - make admin account owner success");
                }
                catch (Exception ex)
                {
                    SingletonLogger.Instance.Error("UploadReportToGoogleDrive\\MAKE ADMIN ACCOUNT OWNER OF UPLOADED FILE", ex);
                    isErrorOccured = true;
                }
                #endregion MAKE ADMIN ACCOUNT OWNER OF UPLOADED FILE

if (model.Officer != default(int))
                    {
                        #region ALLOW OFFICER TO ACCESS UPLOADED FILE
                        OldModels.MWUsers officer = usersBL.GetAll(model.Officer).FirstOrDefault();

                    url = "https://www.googleapis.com/drive/v2/files/" + uploadedFile.Id
                        + "/permissions/"
                        //+ uploadedFile.Owners[0].PermissionId
                    + "?access_token=" + accessToken
                    + "&sendNotificationEmails=" + (doNotify ? "true" : "false")
                    ;

                    request = WebRequest.Create(url);

                    role = "writer";
                    type = "user";
                    value = Officer.EMail;

                    // Create POST data and convert it to a byte array.
                    postData = "{"
                    + "\"role\":\"" + role + "\""
                    + ",\"type\": \"" + type + "\""
                    + ",\"value\": \"" + value + "\""
                        //+ ",\"permissionId\":\"" + uploadedFile.Owners[0].PermissionId + "\""
                        //+ ",\"transferOwnership\": \"" + "true" + "\""
                    + "}";

                    byteArray = Encoding.UTF8.GetBytes(postData);
                    // Set the ContentType property of the WebRequest.
                    request.ContentType = "application/json";
                    // Set the ContentLength property of the WebRequest.
                    request.ContentLength = postData.Length;//byteArray.Length;
                    // Set the Method property of the request to POST.
                    request.Method = "POST";
                    // Get the request stream.
                    dataStream = request.GetRequestStream();
                    // Write the data to the request stream.
                    dataStream.Write(byteArray, 0, byteArray.Length);
                    // Close the Stream object.
                    dataStream.Close();

                    //TRY CATCH - IF TOKEN IS INVALID
                    try
                    {
                        string responseString = GDriveHelper.GetResponse(request);
                        SingletonLogger.Instance.Info("UploadReportToGoogleDrive - make officer writer success");
                    }
                    catch (Exception ex)
                    {
                        SingletonLogger.Instance.Error("UploadReportToGoogleDrive\\ALLOW OFFICER TO ACCESS UPLOADED FILE", ex);
                        isErrorOccured = true;
                    }
                    #endregion ALLOW OFFICER TO ACCESS UPLOADED FILE
                }                    
            }

            if (isErrorOccured)
            {
                SingletonLogger.Instance.Info("UploadReportToGoogleDrive -  report upload to gdrive failed");
            }
            else
            {
                //LogHelper.CreateLogEntry(UserContext.CurrentUser.UserID, "Uploaded " + myFileList.Count + " file(s) on Google Drive.", this.HttpContext.Request);

                SingletonLogger.Instance.Info("UploadReportToGoogleDrive -  report upload to gdrive success");
            }
        }
        catch (Exception ex)
        {
            SingletonLogger.Instance.Info("UploadReportToGoogleDrive - Outer exception", ex);
            isErrorOccured = true;
        }

        return isErrorOccured;

}

暂时还没有答案

 类似资料:
  • 今天我想把我的一个项目从我的开发环境转移到我的生产环境。 当我试图通过FTP上传它时,我已经看到几乎110k文件正在更新。 有人能告诉我这是否真的是必需的,或者我是否错过了一些编译功能等来启动和运行它吗? 干杯,费边

  • 我正在开发一个带有文件上传的web应用程序。 我只是写了一个PHP代码来上传一个图像。 当我运行此代码时,我可以在文件上传时获得输出,如果上传错误 我给了777权限来访问pic文件夹 有什么问题,有什么想法吗,, 类型 Print_R 数组 谢啦

  • 问题内容: 我正在创建用于发送邮件的邮件页面。我需要在发送前附加一些文件。我如何使用AJAX做到这一点?最初,我需要将这些文件存储在服务器中,然后必须发送邮件。通过单个发送按钮即可完成这些操作。 问题答案: 检查以下问题: JavaScript文件上传 如何为我的Web应用程序上传类似Gmail的文件? 什么是最好的多文件JavaScript / Flash文件上传器?

  • 我需要从远程位置读取所有文件并将它们发送到另一个服务,如果成功发送,则删除所有文件。我的代码对于单个文件工作正常,但如果我想在循环中读取所有文件,那么代码不会被执行。 请按以下方式查找代码。在RemoteFileReadImpl类中,我试图读取循环中不起作用的文件。在WebClientUtil类中,我将文件发送到另一个服务。返回成功响应后,我想重命名已读取的文件。

  • 我正试图使用阿拉莫菲尔上传文件。使用文件()时,上传效果很好,但是,我似乎不知道如何使用选项? 这是我的测试: 我的状态代码是415? 此外,如何在上传中发送其他参数? 谢啦 编辑 我没有设置正确的内容类型: 仍然不知道如何发送附加参数随上传。

  • 如何使用selenium webdriver通过窗口提示从本地上传文件? 我想执行以下操作: 点击窗口上的“浏览”选项 从窗口提示符转到保存文件的本地特定位置 选择文件,然后单击“打开”以上传文件。