drive v2 でファイルupload


javascript でgoogle driveにファイルをupload

最初folderと同じように
gapi.client.drive.files.insert
を使ってuploadしようと試みていたのがそもそもの間違い
gapi.client.request
を使えばすんなり成功。

GoogleDriveが管理するドキュメントには2種類あって

  1. GoogleDocument(folder:"application/vnd.google-apps.folder")
  2. 上記以外(jpgとか:"application/octet-stream")

という棲み分けなのかと勝手に理解。
よくよく考えれば本家UIもオペレーション違ってたし。

upload.js
        function gapi_file_upload(){
            var uploadFile = $('#file')[0].files[0];

            var reader = new FileReader();
            reader.readAsBinaryString(uploadFile);

            reader.onload = function(e) {
                var helper = functions.multipert_helper();
/*
=>helper.initial_body_requestは以下のフォーマットで文字列を作成(本家マニュアルより引用)
var multipartRequestBody =
    delimiter +
    'Content-Type: application/json\r\n\r\n' +
    JSON.stringify(metadata) +
    delimiter +
    'Content-Type: ' + contentType + '\r\n' +
    'Content-Transfer-Encoding: base64\r\n' +
    '\r\n' +
    data +
    close_delim;
*/
                var multipartRequestBody = helper.initial_body_request("gfileapi.htm",reader.result);

                var request = gapi.client.request({
                    'path': '/upload/drive/v2/files',
                    'method': 'POST',
                    'params': {
                                'uploadType': 'multipart'
                              },
                    'headers': {
                      'Content-Type': helper.header_content_type()
                    },
                    'body': multipartRequestBody
                });                
                request.execute(function(e){console.log(e)});
            }
        }