简体   繁体   English

使用 GWT 通过 HTTP POST 下载文件

[英]Download file with HTTP POST using GWT

Here's a working code to download a file using 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.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{

            }
        };
    }-*/;

Is there a way to do this in pure Java (GWT) and not JSNI?有没有办法在纯 Java (GWT) 而不是 JSNI 中做到这一点?

This question guided me toward getting this working using JSNI.这个问题引导我使用 JSNI 来完成这项工作。 I don't see the need to do in pure GWT.我认为没有必要在纯 GWT 中做。

The code from the question uses XMLHttpRequest however if the 'payload' is already in the client's browser, it can be placed directly into the Blob.问题中的代码使用 XMLHttpRequest 但是如果“有效负载”已经在客户端的浏览器中,则可以将其直接放入 Blob 中。

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

At time of writing:在撰写本文时:

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