Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle attachment in response with RequestBuilder in GWT

I am making a HTTP POST request from GWT Client to a HTTPServlet. This Servlet is creating a PDF file from request content and writing it to response stream.

Headers of the response stream are:

Content-Disposition: attachment; filename=report.pdf

I want to open this PDF in new window of the user's browser or prompt him to download it.

import com.google.gwt.http.client.*;
...

String url = "http://www.myserver.com/getData?type=3";
RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, URL.encode(url));

try {
  Request request = builder.sendRequest(data, new RequestCallback() {
    public void onError(Request request, Throwable exception) {
       // Couldn't connect to server (could be timeout, SOP violation, etc.)     
    }

    public void onResponseReceived(Request request, Response response) {
      if (200 == response.getStatusCode()) {
          // Process the response in response.getText()
          // Window.open(url, "_blank", "");
      } else {
        // Handle the error.  Can get the status text from response.getStatusText()
      }
    }       
  });
} catch (RequestException e) {
  // Couldn't connect to server        
}

How should I handle response in onResponseRecieved?

like image 401
nishu Avatar asked Sep 02 '11 11:09

nishu


1 Answers

I think in this case you should not use a single RequestBuilder AJAX call. You can rely on the default browser behavior by invoking a normal call and letting the browser handle the PDF response (displaying it with a PDF viewer plugin or opening a Save dialog).

There are several alternatives to achieving this:

  1. If you can pass your data in a GET request (only possible for a small data volume) you can create the URL with the data as GET parameters and then open a new browser window with Window.open() passing the URL with data.

  2. For larger amounts of data you can first POST your data with RequestBuilder to the server to store the data temporaly and in RequestCallback.onResponseReceived() open a new browser window with a short URL like above in alternative 1. On the server side you have to split the PDF generation servlet into two parts: a data store servlet with POST method (i.e. storing the data into the web session) and a PDF render servlet with GET method, which takes the data out of the session (and deleting it) and doesn't need large parameters.

  3. Create a form with method POST, hidden fields for your data and the PDF generation servlet URL. Fill the hidden fields with your data and submit the form programmatically (i.e. FormPanel.submit()). If you create your FormPanel with a target name the browser opens a new window or uses the specified frame to handle the response.

like image 124
vanje Avatar answered Nov 02 '22 23:11

vanje