4
3

More than 5 years have passed since last update.

drive v2 でファイルupload

Last updated at Posted at 2012-12-04

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)});
            }
        }

4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3