我正在连接WCS服务,并且必须将带有XML的HTTP POST请求发送到服务器以检索(二进制)光栅文件。
我设法用jQuery ajax下载文件,但我无法将实际文件内容保存到本地文件系统。
有没有办法实现这个目标?我最好使用浏览器内置的下载管理器来处理下载。
答案 0 :(得分:2)
是的,可以从Javascript中保存文件。基本上它会生成一个包含二进制数据的blob,然后使用HTML5"下载"创建一个指向此blob的链接。属性以指定所需的文件名,最后它模拟此链接上的单击。
// Limited browser support! (latest release versions of Firefox & Chrome are OK)
var DownloadAttributeSupport = 'download' in document.createElement('a');
function showSave(data, name, mimetype) {
var blob, url, builder = new BlobBuilder();
builder.append(data);
if (!mimetype) mimetype = "application/octet-stream";
if (DownloadAttributeSupport) {
blob = builder.getBlob(mimetype);
url = URL.createObjectURL(blob);
var link = document.createElement("a");
link.setAttribute("href",url);
link.setAttribute("download",name||"Download.bin");
// Now I need to simulate a click on the link.
// IE 10 has the better msSaveBlob method and older IE versions do not support the BlobBuilder interface
// and object URLs, so we don't need the MS way to build an event object here.
var event = document.createEvent('MouseEvents');
event.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
link.dispatchEvent(event);
}
您需要查看https://stackoverflow.com/a/13059556/2227298以获取有关不支持HTML5的浏览器的替代代码的更完整答案< a download>