繁体   English   中英

使用 GWT 通过 HTTP POST 下载文件

[英]Download file with HTTP POST using GWT

这是使用 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.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 中。

我的演示解决方案: FileDownloadSpike.java

在撰写本文时:

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);

}-*/;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM