使用Google App Script从Google云端硬盘解压缩文件

时间:2017-07-24 15:42:02

标签: google-apps-script

我需要一个脚本来解压我上传到谷歌硬盘的文件,并将zip文件的内容放回我的谷歌硬盘中。

我遇到了麻烦。它运行时没有错误,但它上传的文件为空。我是Google App Script的新手,所以任何帮助都将不胜感激。感谢。

<!-- increase buffer size to avoid JSF1095 errors -->
<context-param>
    <param-name>javax.faces.FACELETS_BUFFER_SIZE</param-name>
    <param-value>131072</param-value>
</context-param>

1 个答案:

答案 0 :(得分:3)

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:以下功能会上传解压缩的文件并将其转换为Google驱动器格式

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)
   }
}