jQuery / JS GET从一台服务器,POST接收文件到另一台服务器

我们最近购买了许可证,以便在我们的代码中使用其他人的网络服务。 基本上,我需要能够从一个服务器检索文件,然后立即将该文件POST到另一个服务器,并查看响应文本。

这似乎很容易,因为我已经单独完成了这些请求。 我正在尝试从我自己的服务器获取一个简单的文件并将其发布到此API。

这是我正在使用的当前代码。

我发布的API返回基于fileModel参数的错误,因此看起来我没有正确的“数据”变量(例如File)。 我假设GET调用返回的数据变量不是真正的“文件”类型,因此post失败了。

我不确定如何正确创建从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); }); }); 

您无法使用$ .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();