从一台服务器上获取jQuery/JS GET,将接收到的文件发布到另一台服务器上 [英] jQuery/JS GET from one server, POST received file to another
问题描述
我们最近购买了许可,以在我们的代码中使用其他人的Web服务.基本上,我需要能够从一台服务器检索文件,然后立即将该文件发布到另一台服务器,并查看响应文本.
We have recently purchased licenses for the use of some other people's web services in our code. Basically, I need to be able to retrieve a file from one server then immediately POST that file to another server, and view the response text.
这似乎很容易,因为我已经分别完成了许多这些请求.我正在尝试从自己的服务器获取一个简单文件并将其发布到此API进行测试.
It seems easy enough since I've done these requests separately a lot. I'm trying to test with getting a simple file from my own server and post it to this API.
这是我正在使用的当前代码.
Here's the current code I'm working with.
我要发布的API基于fileModel参数返回错误,因此似乎我没有适当的数据"变量(例如File).我假设GET调用返回的数据变量不是真正的文件"类型,因此发布失败.
The API I'm posting through returns an error based on the fileModel parameter, so it would seem like I don't have a proper "data" variable (e.g. File). I'm assuming that the data variable being returned by the GET call is not a true "File" type so the post is failing as a result.
我不确定如何正确创建从GET返回的文件"对象,以便将其正确发布为文件.
I'm not sure how to properly create a "File" object that's returned from GET so that it posts correctly as a file.
$.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);
});
});
推荐答案
使用$.不能真正获得二进制响应.必须使用纯XMLHttpRequest
You can't really get a binary response with $.get you'll have to use plain 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();
这篇关于从一台服务器上获取jQuery/JS GET,将接收到的文件发布到另一台服务器上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!