Javascript 使用GWT下载带有HTTP POST的文件
下面是使用JSNI下载文件的工作代码:Javascript 使用GWT下载带有HTTP POST的文件,javascript,java,gwt,jsni,Javascript,Java,Gwt,Jsni,下面是使用JSNI下载文件的工作代码: public static native void downloadPDF(String payload, String form) /*-{ var xhr = new XMLHttpRequest(); xhr.open('POST', 'http://localhost:8080/template/' + form); xhr.responseType = 'blob'; xhr.sen
public static native void downloadPDF(String payload, String form) /*-{
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost:8080/template/' + form);
xhr.responseType = 'blob';
xhr.send(payload);
xhr.onload = function(e) {
if (this.status == 200) {
var blob = new Blob([this.response], {type: 'image/pdf'});
var a = document.createElement("a");
a.style = "display: none";
document.body.appendChild(a);
var url = $wnd.window.URL.createObjectURL(blob);
a.href = url;
a.download = 'Documo.pdf';
a.click();
window.URL.revokeObjectURL(url);
}else{
}
};
}-*/;
在纯Java(GWT)而不是JSNI中有没有办法做到这一点?这个问题引导我使用JSNI实现这一点。我不认为有必要在纯GWT中这样做 问题中的代码使用XMLHttpRequest,但是如果“有效负载”已经在客户端浏览器中,则可以直接将其放入Blob中 我的演示解决方案: 在编写本报告时:
public static native void download() /*-{
var blob = new Blob(["Hello World"], {type: 'text/plain'});
var a = document.createElement("a");
a.style = "display: none";
document.body.appendChild(a);
//Create a DOMString representing the blob
//and point the link element towards it
var url = window.URL.createObjectURL(blob);
a.href = url;
a.download = 'hello-world.txt';
//programatically click the link to trigger the download
a.click();
//release the reference to the file by revoking the Object URL
window.URL.revokeObjectURL(url);
}-*/;
你可以试试元素2。应该可以。在elemental2中找不到URL.createObjectURL