Click here to Skip to main content
15,867,956 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
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
Posted
Updated 23-Jul-15 11:01am
v2
Comments
Sergey Alexandrovich Kryukov 23-Jul-15 17:45pm    
It depends on the protocol and what you have on that server... No code, based on your information, can really help you. Upload for, say, FTP and HTTP is described in thousands of places, with code samples...
—SA
jyo.net 24-Jul-15 1:41am    
visit url http://www.c-sharpcorner.com/uploadfile/dhananjaycoder/file-upload-in-Asp-Net-mvc-application/

It may help to u
PoonamAswani 24-Jul-15 4:39am    
Thanks for the link...but I have the downloadUrl and the input type file in html won't accept the value of this downloadUrl. The html control doesn't allows to set the value it takes the selected file. So I cannot use input type file control here.

1 solution

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


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. Following is the HTML code we need to add to pass the url to controller

HTML
<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. Following is the code in controller for creating an AuthenticateOauth

C#
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. Following is the method to downloadFile to application server
C#
[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. 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 :)
 
Share this answer
 
Comments
Member 13091966 3-Apr-17 5:19am    
Is there a way to get the complete code for this?

You have already saved me some time, but that would help even more.

Thanks
Member 10419043 22-Apr-18 9:38am    
please give me the full source code

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900