繁体   English   中英

使用Google Drive Rest API上传文件

[英]Upload a file with google drive rest api

我在Google Apps脚本中使用了服务帐户,因此无法使用普通的Google Apps脚本API。

因此,我使用驱动器rest api进行创建,移动,复制等操作,但是我能够使用rest api上传文件。 它上传了一个文件,但没有内容或内容有误。

这是我的代码:

var contentType = data.substring(5, data.indexOf(';')),
            bytes = Utilities.base64Decode(data.substr(data.indexOf('base64,') + 7)),
            blob = Utilities.newBlob(bytes, contentType, file);

  var service = getService();
if (service.hasAccess()) {
    var url = 'https://www.googleapis.com/upload/drive/v3/files?uploadType=media';
    var data = {
        name: name,
        mimeType: "application/pdf",
        parents:  [parent]
    };
    var options = {
        method: 'post',
        contentType: 'application/json',
        body: blob ,
        payload: JSON.stringify(data),
        muteHttpExceptions: true,
        headers: {
            Authorization: 'Bearer ' + service.getAccessToken()
        }
    };
    var response = UrlFetchApp.fetch(url, options);
   var result = JSON.stringify(response.getContentText());
   Logger.log(JSON.stringify(result, null, 2));
    return result["id"];
} else {
    Logger.log(service.getLastError());
}

谢谢

使用Drive API上传文件时,您需要使用files.create方法。 您可以在“ 基本上传”中看到使用javascript代码的参考资料。 另请注意, App Script上传文件使用的是Drive.v2版本的files.insert而不是files.create。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM