Create File with Google Drive Api v3 (javascript)

前端 未结 4 1035
情歌与酒
情歌与酒 2020-11-27 17:28

I want to create a file with content using Google Drive API v3. I have authenticated via OAuth and have the Drive API loaded. Statements like the following work (but produce

4条回答
  •  北海茫月
    2020-11-27 17:59

    Unfortunately, I have not found an answer using only the google drive api, instead I followed Gerardo's comment and used the google request api. Below is a function that uploads a file to google drive.

    var createFileWithJSONContent = function(name,data,callback) {
      const boundary = '-------314159265358979323846';
      const delimiter = "\r\n--" + boundary + "\r\n";
      const close_delim = "\r\n--" + boundary + "--";
    
      const contentType = 'application/json';
    
      var metadata = {
          'name': name,
          'mimeType': contentType
        };
    
        var multipartRequestBody =
            delimiter +
            'Content-Type: application/json\r\n\r\n' +
            JSON.stringify(metadata) +
            delimiter +
            'Content-Type: ' + contentType + '\r\n\r\n' +
            data +
            close_delim;
    
        var request = gapi.client.request({
            'path': '/upload/drive/v3/files',
            'method': 'POST',
            'params': {'uploadType': 'multipart'},
            'headers': {
              'Content-Type': 'multipart/related; boundary="' + boundary + '"'
            },
            'body': multipartRequestBody});
        if (!callback) {
          callback = function(file) {
            console.log(file)
          };
        }
        request.execute(callback);
    }
    

提交回复
热议问题