简体   繁体   中英

Download file with HTTP POST using GWT

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

This question guided me toward getting this working using JSNI. I don't see the need to do in pure 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.

My demo solution: 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);

}-*/;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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