如何使用Javascript将普通/文本文件上传到谷歌驱动器?

时间:2016-09-26 13:51:43

标签: javascript google-drive-api blob

如何将此blob文件上传到我拥有文件夹ID的Google云端硬盘文件夹:

var blob = new Blob([credentialText], {
    type: "text/plain;charset=utf-8;",
});

文档似乎不太清楚。我已经检查了这个link但是没有关于如何发出请求的例子......我也检查了CORS请求但没有帮助。我迷路了:(

提前致谢。

我试过这个并且确实有效:

var createFile = function(name,text,parentId) {
    var auth_token = $rootScope.accessToken;

    const boundary = '-------314159265358979323846';
    const delimiter = "\r\n--" + boundary + "\r\n";
    const close_delim = "\r\n--" + boundary + "--";
    var mimeType = 'text/plain';
    var metadata = { 
      "name" : name,
      "mimeType": 'text/plain',
      "parents": [parentId]
    };  

    var multipartRequestBody =
    delimiter +  'Content-Type: application/json\r\n\r\n' +
    JSON.stringify(metadata) +
    delimiter + 'Content-Type: application/json\r\n\r\n' +
    text +
    close_delim;

    gapi.client.request({ 
        'path': '/upload/drive/v3/files/',
        'method': 'POST',
        'params': {'uploadType': 'multipart'},
        'headers': { 'Content-Type': 'multipart/form-data; boundary="' + boundary + '"', 'Authorization': 'Bearer ' + auth_token, },
        'body': multipartRequestBody 
    }).execute(function(file) { 
        console.log(file);
        console.log("Wrote to file " + file.name + " id: " + file.id); 
    }, function(error){
        console.log(error);
    }); 
}

1 个答案:

答案 0 :(得分:0)

在深入研究前两个问题(herehere)后,我通过部分结合这些问题找到了解决方案:

var createTxtFile = function(name,text,parentId) {
    var auth_token = $rootScope.accessToken;

    const boundary = '-------314159265358979323846';
    const delimiter = "\r\n--" + boundary + "\r\n";
    const close_delim = "\r\n--" + boundary + "--";
    const mimeType = 'text/plain';

    var metadata = { 
      "name" : name,
      "mimeType": mimeType,
      "parents": [parentId]
    };  

    var multipartRequestBody =
    delimiter +  'Content-Type: application/json\r\n\r\n' +
    JSON.stringify(metadata) +
    delimiter + 'Content-Type:'+ mimeType+'\r\n\r\n' +
    text +
    close_delim;

    gapi.client.request({ 
        'path': '/upload/drive/v3/files/',
        'method': 'POST',
        'params': {'uploadType': 'multipart'},
        'headers': { 'Content-Type': 'multipart/mixed; boundary="' + boundary + '"', 'Authorization': 'Bearer ' + auth_token, },
        'body': multipartRequestBody 
    }).execute(function(file) { 
        console.log(file);
        console.log("Wrote to file " + file.name + " id: " + file.id); 
    }, function(error){
        console.log(error);
    }); 
}