如何将选定的文件从Google云端硬盘上传到应用服务器 [英] How to upload selected file from Google Drive to application server

查看:109
本文介绍了如何将选定的文件从Google云端硬盘上传到应用服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经构建了一个对用户进行身份验证的应用程序,并允许从他的google驱动器中选择文件。我在javascript中有所选文件的downloadUrl。但是我想把这个文件上传到我的应用服务器。

有人可以帮我把代码从客户端(javascript)移到服务器端(控制器),这样我就可以上传这个文件。



请帮忙...... 紧急!!



谢谢

I have built an application which authenticates user and allows to select files from his google drive. I have the downloadUrl in javascript for selected file. But I want to upload this file to my application server.
Can someone please help me get the code for moving selected file from client side (javascript) to server side (controller), so that I can upload this file.

Please help...its urgent!!

Thanks

推荐答案

1。以下是在Javascript中从createPicker方法调用的回调方法





1. Following is the callback method to be called from createPicker method in Javascript


function onPickerAction(data) {              
              if (data.action === google.picker.Action.PICKED) {
                  
                  var id = data.docs[0].id;
                  var doc = data[google.picker.Response.DOCUMENTS][0];
                  url = doc[google.picker.Document.URL];                  

                  var linkTag = document.getElementById('link');                  
                  linkTag.href = url;
                  linkTag.textContent = doc.name;
                  document.getElementById("fileName").value = doc.name;

                  var request = new XMLHttpRequest();
                  request.open('GET', 'https://www.googleapis.com/drive/v2/files/' + id);
                  request.setRequestHeader('Authorization', 'Bearer ' + gapi.auth.getToken().access_token);
                  request.addEventListener('load', function () {
                      var item = JSON.parse(request.responseText);
                      alert(request.responseText);
                      document.getElementById('fileLink').value = item.downloadUrl;
                      console.log(item);
                  });

                  request.send();
              }
          }





2。以下是我们需要添加以将网址传递给控制器​​的HTML代码





2. Following is the HTML code we need to add to pass the url to controller

<div id="result"></div>
     <input type="image" src="~/Content/google_drive_logo.jpg" width="150px" height="100px" onclick=" onApiLoad() "/>
    <a id="link" target="_blank"></a>
    <div>
         @using (Html.BeginForm("downloadFile", "GoogleDrive", null, FormMethod.Post))
        {
            <input type="hidden" name="_fileResourceDownloadUrl" id="fileLink" />
             <input type="hidden" name="fileNameToSave" id="fileName"/>
            <input type="submit" value="Submit Link"/>
        }
     </div>





3。以下是控制器中用于创建AuthenticateOauth的代码





3. Following is the code in controller for creating an AuthenticateOauth

public static DriveService AuthenticateOauth(string clientId, string clientSecret, string userName)
        {
            string[] scopes = new string[] { DriveService.Scope.Drive,                                               DriveService.Scope.DriveAppdata,                                DriveService.Scope.DriveAppsReadonly,                                             DriveService.Scope.DriveFile,                                             DriveService.Scope.DriveMetadataReadonly,                                        DriveService.Scope.DriveReadonly,                                            DriveService.Scope.DriveScripts };  


            try
            {
                // here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
                UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret }
                                                                                             , scopes
                                                                                             , userName
                                                                                             , CancellationToken.None
                                                                                             , new FileDataStore("FOLDER_NAME_TO_STORE_AUTHENTICATION_TOKEN_ON_SERVER")).Result;

                DriveService service = new DriveService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "APPL_NAME_AS_PER_API_CONSOLE",
                });
                return service;
            }
            catch (Exception ex)
            {

                Console.WriteLine(ex.InnerException);
                return null;

            }

        }





4。以下是将文件下载到应用程序服务器的方法



4. Following is the method to downloadFile to application server

[HttpPost]
       public ActionResult downloadFile(string _fileResourceDownloadUrl,string fileNameToSave)
       {
           // Connect with Oauth2 Ask user for permission
           string CLIENT_ID = "CLIENT_ID";
           string CLIENT_SECRET = "CLIENT_SECRET";
           string MY_EMAIL_ADD = "EMAIL_FROM_DEVELOPER_CONSOLE";

           if (!String.IsNullOrEmpty(_fileResourceDownloadUrl) )
           {
               try
               {
                   DriveService _service = AuthenticateOauth(CLIENT_ID, CLIENT_SECRET, MY_EMAIL_ADD);
                   var x = _service.HttpClient.GetStringAsync(_fileResourceDownloadUrl);

                   string arrBytes = x.Result;


                   System.IO.File.WriteAllText(
                       @"PATH_TO_SAVE_FILE" + fileNameToSave, arrBytes);

                   return View("VIEW_TO_RETURN");
               }
               catch (AggregateException e)
               {
                   return View("ERROR_VIEW");
               }
               catch (InvalidOperationException e)
               {
                   return View("ERROR_VIEW");
               }
           }
           else
           {
               return null;
           }
       }





5.您需要创建一个客户端ID谷歌开发者控制台安装的应用程序。这将为您提供不需要更新的Redirect Uri。




希望这可以节省一些人的时间......因为我花了很长时间到达这里...如果有人需要完整的代码,请告诉我...享受:)



5. You need to create a client ID in google developer console for installed applications. This will give you Redirect Uri's which don't need to be updated.


Hope this saves someone's time...as it took me a long time to reach here... Please let me know if anyone needs the complete code... Enjoy :)


这篇关于如何将选定的文件从Google云端硬盘上传到应用服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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