2017-07-24 132 views
3

我需要一個腳本,將解壓縮文件,我已經上傳到我的谷歌驅動器,並將zip文件的內容放回我的谷歌驅動器。使用谷歌應用腳​​本從谷歌驅動器解壓縮文件

我遇到了麻煩。它運行時沒有錯誤,但它上傳的文件是空的。我對Google App腳本非常陌生,所以任何幫助都將不勝感激。謝謝。

function unZipIt() { 
    var theFolder = DriveApp.getFolderById('0B9jgHw-WmzvfRS1ZZEhTc3Byak0') 
    var theFile = theFolder.getFilesByName('Dock to Stock Weekly_Dock to Stock AMP.zip') 
    var fileBlob = theFile.next().getBlob() 

    fileBlob.setContentType("application/zip") 

    var unZippedfile = Utilities.unzip(fileBlob) 
    var fileId = SpreadsheetApp.create(unZippedfile).getId(); 
    var file = DriveApp.getFileById(fileId); 
    DriveApp.addFile(file) 
    } 

回答

0

SpreadsheetApp.create需要一個字符串,它用於使用傳遞的字符串創建新的電子表格。請參考以下代碼解壓並上傳Google驅動器中的文件。

編輯1:下面的函數將以其原始格式上傳解壓縮的文件。

function unZipIt() { 
    var theFolder = DriveApp.getFolderById('0B9jgHw-WmzvfRS1ZZEhTc3Byak0'); 
    var theFile = theFolder.getFilesByName('Dock to Stock Weekly_Dock to Stock AMP.zip'); 
    var fileBlob = theFile.next().getBlob(); 
    fileBlob.setContentType("application/zip"); 
    var unZippedfile = Utilities.unzip(fileBlob); 
    var newDriveFile = DriveApp.createFile(unZippedfile[0]); 
    Logger.log(newDriveFile.getId()) 
} 

編輯2:以下功能將上傳解壓文件,並將其轉換成谷歌驅動器格式

function unZipIt() { 
    var theFolder = DriveApp.getFolderById('0B5JsAY8jN1CoWnhxU0Izemp6WW8'); 
    var theFile = theFolder.getFilesByName('test.zip'); 
    var fileBlob = theFile.next().getBlob(); 
    fileBlob.setContentType("application/zip"); 
    var unZippedfile = Utilities.unzip(fileBlob); 
    var newDriveFile = DriveApp.createFile(unZippedfile[0]); 
    convertToGoogleDocs(newDriveFile.getId()) 
} 

function convertToGoogleDocs(fileId) { 
    try{ 
    var originalFile = DriveApp.getFileById(fileId); 
    var uploadFile = JSON.parse(UrlFetchApp.fetch(
     "https://www.googleapis.com/upload/drive/v2/files?uploadType=media&convert=true", 
     { 
     method: "POST", 
     contentType: originalFile.getMimeType(), 
     payload: originalFile.getBlob().getBytes(), 
     headers: { 
      "Authorization" : "Bearer " + ScriptApp.getOAuthToken() 
     }, 
     muteHttpExceptions: true 
     } 
    ).getContentText()); 

    // Remove the file extension from the new google file name 
    var googleFileName = originalFile.setName(originalFile.getName().substr(0, originalFile.getName().lastIndexOf("."))); 

    // Update the name of the Google file created from the original file 
    DriveApp.getFileById(uploadFile.id).setName(googleFileName); 
    var files = DriveApp.getFileById(uploadFile.id); 
    } 
    catch(e){ 
     Logger.log(e) 
    } 
} 
+0

@Christopher,我已經更新了答案! – Ritz

+1

它的工作原理!你真了不起,謝謝! –

相關問題