quarks
quarks

Reputation: 35276

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?

Upvotes: 2

Views: 734

Answers (1)

Peter L
Peter L

Reputation: 3343

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

}-*/;

Upvotes: 1

Related Questions