通过 AppScript 从 Google 驱动器上传到 BOX

Uploading from Google Drive to BOX through AppScript

目前正在研究 google sheet 并执行一个脚本,该脚本将文件从云端硬盘上传到 BOX。 我获得了身份验证(我能够通过连接到 API 的脚本获取文件夹列表)但是当我到达上传部分时,我收到一个空请求并且文件没有上传到目标文件夹

我的脚本如下:

function uploadFile() {

  var boundary = "test";
  var blob = DriveApp.getFileById('<I got my file ID here>').getBlob();
  var service = getService();

  var attributes = "{\"name\":\"test document.pdf\", \"parent\":{\"id\":\"<I got my folder ID here>\"}}";

  var requestBody = Utilities.newBlob(
    "--"+boundary+"\r\n"
    + "Content-Disposition: form-data; name=\"attributes\"\r\n\r\n"
    + attributes+"\r\n"+"--"+boundary+"\r\n"
    + "Content-Disposition: form-data; name=\"file\"; filename=\""+blob.getName()+"\"\r\n"
  + "Content-Type: " + blob.getContentType()+"\r\n\r\n").getBytes()
  .concat(blob.getBytes())
  .concat(Utilities.newBlob("\r\n--"+boundary+"--\r\n").getBytes());

  var options = {
    method: "post",
    contentType: "multipart/form-data; boundary="+boundary,
    payload: requestBody,
    muteHttpExceptions: true,
    headers: {'Authorization': 'Bearer ' + service.getAccessToken()}
  };

  var request = UrlFetchApp.fetch("https://upload.box.com/api/2.0/files/content", options);

  Logger.log(request.getContentText()); // empty response

}

谢谢

修改点:

  • 查看BOXAPI的“上传文件”官方文档时,发现了如下curl示例。 Ref

      $ curl -i -X POST "https://upload.box.com/api/2.0/files/content" \
           -H "Authorization: Bearer <ACCESS_TOKEN>" \
           -H "Content-Type: multipart/form-data" \
           -F attributes="{"name":"Contract.pdf", "parent":{"id":"11446498"}}" \
           -F file=@<FILE_NAME>
    
  • multipart/form-data的请求是运行时,似乎在Google Apps Script中,内容类型是自动创建的,包括边界。

当上面的curl命令转换为Google Apps Script时,变成如下。

修改后的脚本:

function uploadFile() {
  var blob = DriveApp.getFileById('<I got my file ID here>').getBlob();
  var service = getService();
  var attributes = {"name":"test document.pdf", "parent":{"id":"<I got my folder ID here>"}};
  var requestBody = {attributes: Utilities.newBlob(JSON.stringify(attributes), "application/json"), file: blob};
  var options = {
    method: "post",
    payload: requestBody,
    muteHttpExceptions: true,
    headers: {'Authorization': 'Bearer ' + service.getAccessToken()}
  };
  var request = UrlFetchApp.fetch("https://upload.box.com/api/2.0/files/content", options);
  Logger.log(request.getContentText());
}

注:

  • 在此示例脚本中,假设您的 service.getAccessToken() 访问令牌可用于使用 API 上传文件。请注意这一点。

参考文献: