我正在使用OGRE web client将GeoJSON文本数据转换为ESRI shapefile。为此,我在Ajax中使用了POST请求。
var data = { "type": "FeatureCollection",
"features": [{
"type": "Feature",
"geometry": { "type": "Point", "coordinates": [102.0, 0.5] },
"properties": { "prop0": "value0" }
}]
};
function sendPost() {
$.ajax({
type: "POST",
url: 'http://ogre.adc4gis.com/convertJson',
data: {json:JSON.stringify(data)},
success: success
});
}
POST请求的响应是多个文件(见图):
我该如何应对这种反应?我想将文件添加到ZIP文件并下载。我想我可以通过使用JSZip和FileSaver库来做到这一点。应该是这样,但我不知道如何处理响应:
function success(result) {
console.log(result);
var zip = new JSZip();
zip.file = ("file1.shp", result[--file1 in the response--])
var content = zip.generate({type:"blob"});
saveAs(content, "test.zip")
}
需要一些帮助 !! :)
编辑:
尝试使用XHR请求时,我似乎找不到如何正确地将JSON作为文本传递给URL的方法,从而使URL起作用:
params = {
json: JSON.stringify(data)
}
function formatParams( params ){
return "?" + Object
.keys(params)
.map(function(key){
return key+"="+params[key]
})
.join("&")
}
var url_long = "http://ogre.adc4gis.com/convertJson";
var url = url_long + "?" + formatParams(params);
最佳答案
看起来结果已经是一个zip文件。如果只想触发下载,则只需要FileSaver。您唯一需要做的就是获取二进制内容。如果没有进一步的配置,$.ajax
将尝试将内容解码为UTF8并破坏内容。这就是您需要的Blob(或Uint8Array)。
从this question,您可能需要使用原始XHR请求。
如果您要过滤zip文件的内容,则不会
var zip = new JSZip();
zip.file("file1.shp", result[--file1 in the response--])
反而
var zip = new JSZip(result);
// keep file1, remove file2, etc
zip.remove("file2.shp")
编辑:这是如何使用XMLHttpRequest发布json:
var formData = new FormData();
formData.append('json', JSON.stringify(data));
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://ogre.adc4gis.com/convertJson");
xhr.responseType = "arraybuffer"; // ask for a binary result
xhr.onreadystatechange = function(evt) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
var zip = new JSZip(xhr.response);
console.log("success, got", Object.keys(zip.files));
} else {
console.log("http call error");
}
}
};
xhr.send(formData);
哪个显示
success, got Array [ "OGRGeoJSON.dbf", "OGRGeoJSON.prj", "OGRGeoJSON.shp", "OGRGeoJSON.shx" ]