39

API を介して Google ドライブにファイルを挿入する方法についてサポートが必要です。この目的のための API ドキュメントには、http ポスト リクエストを介してファイルの実際の本文を送信する方法が明確に説明されていません。

4

5 に答える 5

65

挿入操作に関するドキュメントには、すでに多数のプログラミング言語の例が含まれています。ここでは、Google Drive API の HTTP ベースのプロトコルを使用してそれを行う方法を示します。

まず、新しいファイル メタデータを Drive エンドポイントに POST します。ファイル リソース JSON オブジェクトの形式である必要があります。

POST /drive/v2/files HTTP/1.1
Host: www.googleapis.com
Authorization: Bearer <OAuth 2.0 access token here>
...

{
  "title": "file_name.extension",
  "mimeType": "mime/type",
  "description": "Stuff about the file"
}

応答本文は、新しく作成されたファイル リソースの JSON 表現になります。次のようになります。

{
  "kind": "drive#file",
  "id": string,
  "etag": etag,
  "selfLink": string,
  "title": "file_name",
  "mimeType": "mime/type",
  "description": "Stuff about the file"
  ...
  "downloadUrl": string,
  ...
}

これは、ファイル エントリが作成されたことの確認です。次に、コンテンツをアップロードする必要があります。そのためには、上記のレスポンスのid JSON 属性で指定されたファイルの ID を取得し、OAuth 2.0 承認済みリクエストで実際のファイルのコンテンツをアップロード エンドポイントに PUT する必要があります。次のようになります。

PUT /upload/drive/v2/files/{id}?uploadType=media HTTP/1.1
Host: www.googleapis.com
Authorization: Bearer <OAuth 2.0 access token here>
Content-Type: mime/type

<file content here>

あなたは終わった:)

コンテンツと同時にファイルのメタデータをポストするマルチパート リクエストを使用して、1 つの POST リクエストでこれを行う方法もあります。次に例を示します。

POST /upload/drive/v2/files HTTP/1.1
Host: www.googleapis.com
Authorization: Bearer <OAuth 2.0 access token here>
Content-Type: multipart/form-data; boundary=287032381131322
...

--287032381131322
Content-Type: application/json

{
  "title": "file_name.extension",
  "mimeType": "mime/type",
  "description": "Stuff about the file"
}
--287032381131322
Content-Type: mime/type

<file content here>
--287032381131322--

応答には、新しく作成されたファイルのメタデータが含まれます。要求のサブパートでContent-Transfer-Encoding: base64ヘッダーを使用して、ファイルのデータを Base 64 エンコードとして渡すこともできます。

最後に、大きなファイルをアップロードしたり、一時停止/再開機能を提供したり、不安定なインターネット接続でファイルをアップロードしたりするのに便利な再開可能なアップロード プロトコルもあります。

追伸: これのほとんどは、ドライブのファイル アップロード ドキュメントに記載されています。

于 2012-04-25T20:54:10.767 に答える
17

説明してくれてありがとう!これには、くだらない Google SDK ドキュメントをめぐるのに何時間もかかりました (申し訳ありませんが、暴言を吐き出さなければなりませんでした)。

テキストファイルを更新するために作成した関数を次に示します(ご覧のとおり、htmlを更新しています)。

  function gd_updateFile(fileId, folderId, text, callback) {

    const boundary = '-------314159265358979323846';
    const delimiter = "\r\n--" + boundary + "\r\n";
    const close_delim = "\r\n--" + boundary + "--";

    var contentType = "text/html";
    var metadata = {'mimeType': contentType,};

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

    if (!callback) { callback = function(file) { console.log("Update Complete ",file) }; }

    gapi.client.request({
        'path': '/upload/drive/v2/files/'+folderId+"?fileId="+fileId+"&uploadType=multipart",
        'method': 'PUT',
        'params': {'fileId': fileId, 'uploadType': 'multipart'},
        'headers': {'Content-Type': 'multipart/mixed; boundary="' + boundary + '"'},
        'body': multipartRequestBody,
        callback:callback,
    });
  }

これは、Google の例 (アップロードからのバイナリ ファイルを使用) のマッシュアップであり、上記の @Nivco からの素晴らしい説明です。

于 2012-12-21T07:21:11.400 に答える
8

4年経った今でも、これを理解するのは困難です。画像のアップロードをサポートするために、@ user1158023 の回答を受け取りました。私は API v3 と superagent.js を使用して私を助けています (gapi.client.request が content.googleapis.com にリクエストを送信しているため!?)。うまくいけば、誰かがこれが役に立つと思うかもしれません。

function gd_uploadFile(name, contentType, data, callback) {
    const boundary = '-------314159265358979323846';
    const delimiter = "\r\n--" + boundary + "\r\n";
    const close_delim = "\r\n--" + boundary + "--";

    contentType = contentType || "text/html";
    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';

    //Transfer images as base64 string.
    if (contentType.indexOf('image/') === 0) {
        var pos = data.indexOf('base64,');
        multipartRequestBody += 'Content-Transfer-Encoding: base64\r\n' + '\r\n' +
            data.slice(pos < 0 ? 0 : (pos + 'base64,'.length));
    } else {
        multipartRequestBody +=  + '\r\n' + data;
    }
    multipartRequestBody += close_delim;

    if (!callback) { callback = function(file) { console.log("Update Complete ", file) }; }

    superagent.post('https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart').
        set('Content-Type', 'multipart/form-data;  boundary="' + boundary + '"').
        set('Authorization', 'Bearer ' + gapi.auth.getToken().access_token).
        send(multipartRequestBody).
        end(function () {
            console.log(arguments);
        });
}

//On upload
$('#file')[0].onchange = function () {
    var file = $('#file')[0].files[0];
    if (file && file.type === 'image/jpeg') {
        var reader = new FileReader();
        reader.onloadend = function () {
            var data = reader.result;
            gd_uploadFile('img.jpg', 'image/jpeg', data, function () {
                console.log(arguments);
            });
        }
        reader.readAsDataURL(file);
    }
};

index.html

...
<form>
    <span>Upload: </span><input id="file" type="file" name="myFile">
</form>
...
于 2016-01-11T21:42:31.073 に答える
3

drive gapis v3 のより良い例があればいいのに...で作成された既存のファイルに新しいコンテンツをアップロードする方法を理解するのに時間がかかりました

gapi.client.drive.files.create({ "name" : "savefile.txt" }).execute(function(file) { console.log("Created file " + file.name + " id: " + file.id); });

しかし、最終的には、fileIdをパスに追加し、メソッドをPATCHに変更するという「幸運な」組み合わせを試しました

function uploadFile(id, text)                                                                                                                                                          
{
  var auth_token = gapi.auth.getToken().access_token;

  const boundary = '-------314159265358979323846';
  const delimiter = "\r\n--" + boundary + "\r\n";
  const close_delim = "\r\n--" + boundary + "--";

  var metadata = { 
      description : 'savefile for my game',
      'mimeType': 'application/json'
  };  

  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/'+id,
     'method': 'PATCH',
     'params': {'fileId': id, 'uploadType': 'multipart'},
     'headers': { 'Content-Type': 'multipart/form-data; boundary="' + boundary + '"', 'Authorization': 'Bearer ' + auth_token, },
     'body': multipartRequestBody 
     }).execute(function(file) { console.log("Wrote to file " + file.name + " id: " + file.id); }); 
}

しかし、https://developers.google.com/drive/v3/reference/files/updateのドキュメント全体が私にとって意味をなすようになったと思います:-)

于 2016-05-02T20:09:56.923 に答える