如何通过Google App脚本从Google云端存储获取上传的文件网址

时间:2019-05-30 05:07:57

标签: google-apps-script google-cloud-platform google-cloud-storage

我正在构建Google App Script产品,该产品可将pdf文件上传到Google Cloud Storage,并且效果很好(感谢tutorial)。但是我无法获取上传的文件URL。

这是我的uploadFileToGCS()函数:

function uploadFileToGCS() {

  var service = getService();
  if (!service.hasAccess()) {
    Logger.log("Please authorize %s", service.getAuthorizationUrl());
    return;
  }

  var blob = DriveApp.getFileById(params.DRIVE_FILE).getBlob();
  var bytes = blob.getBytes();

  var url = 'https://www.googleapis.com/upload/storage/v1/b/BUCKET/o?uploadType=media&name=FILE'
    .replace("BUCKET", params.BUCKET_NAME)
    .replace("FILE", encodeURIComponent(params.FILE_PATH));

  var response = UrlFetchApp.fetch(url, {
    method: "POST",
    contentLength: bytes.length,
    contentType: blob.getContentType(),
    payload: bytes,
    headers: {
      Authorization: 'Bearer ' + service.getAccessToken()
    }
  });

  var result = JSON.parse(response.getContentText());
  Logger.log(JSON.stringify(result, null, 2));
}

响应日志:Logger.log(JSON.stringify(result, null, 2));

19-05-29 21:28:19:726 PDT] {
  "kind": "storage#object",
  "id": "bucket_name/folder_name/file_name.pdf/1559190499625016",
  "selfLink": "https://www.googleapis.com/storage/v1/b/bucket_name/o/folder_name/file_name.pdf",
  "name": "folder_name/file_name.pdf",
  "bucket": "bucket_name",
  "generation": "1559190499625016",
  "metageneration": "1",
  "contentType": "application/pdf",
  "timeCreated": "2019-05-30T04:28:19.624Z",
  "updated": "2019-05-30T04:28:19.624Z",
  "storageClass": "MULTI_REGIONAL",
  "timeStorageClassUpdated": "2019-05-30T04:28:19.624Z",
  "size": "101396",
  "md5Hash": "hash",
  "mediaLink": "https://www.googleapis.com/download/storage/v1/b/bucket_name/o/folder_name/file_name.pdf?generation=1559190499625016&alt=media",
}

当我单击到mediaLink时,浏览器会自动下载我的pdf文件,这不是我想要的。

那么如何通过GAS从Google Cloud Storage获取上传的URL文件? 欢迎任何建议!

1 个答案:

答案 0 :(得分:0)