2017-07-24 167 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

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

相关问题