Google Drive Api服务帐户。创建文件时出错(可能归因于base64)

时间:2019-03-06 16:24:37

标签: google-api google-drive-api jwt

我已经创建了一个文件夹和一个文件,并具有允许任何Internet用户访问文件的权限。我曾经认为上传本身可以正常工作。不幸的是,当我使用

  

https://drive.google.com/uc?export=view&id= {file.id}

命令,我看到的只是一个黑色正方形,当我尝试通过downloadLink文件的属性下载时,甚至无法打开它。

所以,这是我的代码

private static String initiateResumable(string base64, string fileType){
    String endpoint ='https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable';

    map<String, Object> md = new map<String, Object>();

    md.put('name', 'demofile'); 
    md.put('parents', '[' + folderId + ']'); 

    String metadata = JSON.serialize(md);

    Integer size = Math.min(2000000, base64.length());

//return an HttpRequest object of POST method with
// Authorization token provided (JWT is used)
    HttpRequest req = createRequest('post');

    req.setEndpoint(endpoint);

    req.setHeader('Content-Type', 'application/json; charset=UTF-8');
    req.setHeader('Content-Length', String.valueOf(metadata.length()));
    req.setHeader('X-Upload-Content-Type', fileType);
    req.setHeader('X-Upload-Content-Length', String.valueOf(size));

    req.setBody(metadata);

    HttpResponse res = (new Http()).send(req);

    return res.getHeader('Location');
}

private static File sendFile(String base64, String fileType, String endpoint){
    Integer size = Math.min(2000000, base64.length());
    HttpRequest req = createRequest('put');
    HttpResponse res;

    req.setEndpoint(endpoint);

    req.setHeader('Content-Type', fileType);

    while(! String.isBlank(base64)){
        final string buffer = base64.left(size);
        base64 = base64.removeStart(buffer);

        req.setHeader('Content-Length', String.valueOf(buffer.length()));
        req.setBody(buffer);

        res = (new Http()).send(req);
    }

    return (File)JSON.deserialize(res.getBody(), File.class);
}

我相信是因为base64格式,但是我可能错了

以下代码发生相同的错误:

    HttpRequest req = createRequest('get');
    req.setEndpoint('https://www.googleapis.com/upload/drive/v3/files?uploadType=media');

    req.setHeader('Content-Type', fileType);
    req.setHeader('Content-Length',String.valueOf(base64.length()));
    req.setHeader('Content-Transfer-Encoding', 'base64');

    req.setBody(base64);

    HttpResponse res = (new Http()).send(req);

    File file = (File) JSON.deserialize(res.getBody(), File.class);

    return file;

这是Salesforce的Apex,因此无法用于任何框架,但是我相信语法非常简单

提前

10q

0 个答案:

没有答案