0

私たちは最近、私たちのコードで他の人の Web サービスを使用するためのライセンスを購入しました。基本的に、あるサーバーからファイルを取得し、すぐにそのファイルを別のサーバーに POST し、応答テキストを表示できる必要があります。

私はこれらのリクエストを別々にたくさん行ってきたので、それは十分に簡単に思えます。自分のサーバーから単純なファイルを取得してテストし、この API に投稿しようとしています。

ここに私が取り組んでいる現在のコードがあります。

私が投稿している API は、fileModel パラメータに基づいてエラーを返すため、適切な「データ」変数 (File など) がないように見えます。GET 呼び出しによって返されるデータ変数が真の「ファイル」タイプではないため、結果として投稿が失敗していると想定しています。

ファイルとして正しく投稿されるように、GET から返される「ファイル」オブジェクトを適切に作成する方法がわかりません。

$.get( "http://localhost/myfile.png", function( data ) {
    var sendData = {
        token : "mytokenhere",
        fileModel : data,
        title : "Cylinder1",
        description: "Cylinder1",
        private: true,
    };
    $.post( "https://api.url.com/", sendData)
        .done(function( data ) {
            alert( "Data Loaded: " + data );
        })
        .fail( function(xhr, textStatus, errorThrown) {
            alert(xhr.responseText);
        });
});
4

1 に答える 1

2

$.get でバイナリ応答を実際に取得することはできません。プレーンな XMLHttpRequest を使用する必要があります。

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
    if (this.readyState == 4 && this.status == 200){
        //this.response is what you're looking for
        var data = new FormData();
        data.append('fileModel', this.response);
        data.append('description', "Cylinder1");
        data.append('private', true);
        data.append('title', "Cylinder1");
        data.append('token', "mytokenhere");
        $.ajax({
            url:'',
            type: 'post',
            data: data,
            contentType: false,
            processData: false
        })
        .done(function( data ) {
            alert( "Data Loaded: " + data );
        })
        .fail( function(xhr, textStatus, errorThrown) {
            alert(xhr.responseText);
        });
    }
}
xhr.open('GET', 'http://localhost/myfile.png');
xhr.responseType = 'blob';
xhr.send();      
于 2013-09-28T14:11:05.620 に答える