2015-05-11 3 views
0

Второй вопрос, который я опубликовал. все еще очень новый для веб-программирования, поэтому извините мое невежество.Доступ к локальной файловой системе - решения?

У меня есть веб-javascript, который обращается к учетной записи пользователя Gmail и загружает вложения в папку локальных загрузок, как указано в Chrome.

Эти файлы затем переносятся вручную в другой каталог, и скрипт Excel VBA обрабатывает файлы.

Хотелось бы пропустить шаг переноса вручную и сохранить файлы непосредственно в папку, на которую смотрит Excel. Я могу заставить скрипт Excel перемещать файлы, но он работает только в том случае, если пользователь не изменил местоположение папки загрузки по умолчанию Chrome, поэтому он не является надежным.

Я считаю, что это невозможно с помощью javascript, но возможно ли это на других языках или мне нужен совершенно другой подход? если это возможно с другими языками, какой из них и какие методы мне нужно искать?

Это раздел загрузки кода, как он стоит на минуту по желанию пользователя, OmegaStripes ниже:

<html> 

<head>Google Drive File Download Process: 
    <meta http-equiv="Content-type" content="text/html;charset=UTF-8"> 
    <script type="text/javascript"> 
     var CLIENT_ID = 'XXXXXXXXXXX';//removed for privacy 
     var SCOPES = 'https://www.googleapis.com/auth/drive'; 

     /** 
     * Called when the client library is loaded to start the auth flow. 
     */ 

     function handleClientLoad() { 
      window.setTimeout(checkAuth, 1); 
     } 

     /** 
     * Check if the current user has authorized the application. 
     */ 

     function checkAuth() { 
      gapi.auth.authorize({ 
        'client_id': CLIENT_ID, 
        'scope': SCOPES, 
        'immediate': true 
       }, 
       handleAuthResult); 
     } 

     /** 
     * Called when authorization server replies. 
     * 
     */ 

     function handleAuthResult(authResult) { 
      var authButton = document.getElementById('authorizeButton'); 
      var filePicker = document.getElementById('filePicker'); 
      authButton.style.display = 'none'; 
      filePicker.style.display = 'none'; 
      if (authResult && !authResult.error) { 
       // Access token has been successfully retrieved, requests can be sent to the API. 
       filePicker.style.display = 'block'; 
       filePicker.onclick = downloadFile; // to allow for manual start of downloads 
       window.setTimeout(downloadFile(), 5000); 

      } else { 
       // No access token could be retrieved, show the button to start the authorization flow. 
       authButton.style.display = 'block'; 
       authButton.onclick = function() { 
        gapi.auth.authorize({ 
          'client_id': CLIENT_ID, 
          'scope': SCOPES, 
          'immediate': false 
         }, 
         handleAuthResult); 
       }; 
      } 
     } 

     /** 
     * Start the file download. 
     * 
     * 
     */ 

     function downloadFile() { 
      console.log("call drive api"); 
      gapi.client.load('drive', 'v2', makeRequest); 
     } 




     function makeRequest() { 
      console.log("make request"); 
      var request = gapi.client.drive.files.list(); 
      request.execute(function(resp) { 

       var x = []; //array for revised list of files to only include those not in the trash and those which have a suffix #FHM# 
       for (i = 0; i < resp.items.length; i++) { 
        if (resp.items[i].labels.trashed != true && resp.items[i].title.substring(0, 5) == "#FHM#") { 
         x.push([resp.items[i].title, resp.items[i].webContentLink, resp.items[i].id]); 
        } 
       } 

       if (x.length == 0) { 
        document.getElementById("filePicker").value = "There are no files to download"; 
       } 


       for (i = 0; i < x.length; i++) { 
        console.log(x.length); 
        var dlUrl = x[i][1]; 
        fileIdentity = x[i][2]; 
        downloadUrl(dlUrl); 
        trashFile(fileIdentity); 

        filePicker.style.display = 'none'; 
        document.getElementById("bodyText").innerHTML = "<br>Download " + (i + 1) + " of " + x.length + " completed."; 
       } 


      }); 

      //window.setTimeout(function() { 
      // self.close; 
      //}, 5000); 

     } 

     function downloadUrl(url) { 
      var iframe = document.createElement("iframe"); 
      iframe.src = url; 
      iframe.style.display = "none"; 
      document.body.appendChild(iframe); 
     } 

     function trashFile(id) { 
      var requestTrash = gapi.client.drive.files.trash({ 
        'fileId': id 
       }); 
      requestTrash.execute(function(resp) {}); 
     } 
    </script> 
    <script type="text/javascript" src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script> 
</head> 


<body> 
    <!--Add buttons for the user to start the process --> 
    <input type="button" id="filePicker" style="display: none" value="If download does not start after 5 seconds, click here" /> 
    <input type="button" id="authorizeButton" style="display: none" value="Authorize" /> 
    <b id="bodyText"></b> 
</body> 

благодаря

+0

Не могли бы вы поделиться своим веб-javascript, он может быть реализован с использованием HTA/JScript, которые имеют полный доступ к FS, или конвертируются и помещаются прямо в ваш VBA. – omegastripes

ответ

0

Ваш код может попытаться скопировать файлы, и если они не удались, попросите пользователя указать правильный путь к извлеченным файлам. Вы правы, это невозможно сделать с помощью Javascript. Если вы хотите, чтобы не спрашивать пользователя о пути, вы можете реализовать модуль для поиска файла.

Есть ли способ узнать, был ли извлечен файл? Если это так, вы можете использовать эти знания, чтобы узнать, должен ли недостаток успешного копирования инициировать поиск файла или запрос на путь к файлу.

+1

да, хорошая идея. Я могу знать, есть ли файл, поскольку все файлы переименованы для включения суффикса # FHM #, так что это легко проверить. поэтому я проверю стандартное место для загрузки файлов с # FHM #, затем выполните поиск, если нет - Nice thanks –

+0

Я рад, что смог помочь –

Смежные вопросы