Call servlet from GWT with post data and download file generated by the servlet

Viewed 13533

I have my ExportServlet, which are generating XLSX files (Excel) which my user will request from my GWT application by clicking a export button.

If I use the GET approach, the user are prompted to download the file. The code looks like this:

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException
{
    try
    {
        byte[] xlsx = createTest("");
        sendXLSX(resp, xlsx, "test.xlsx");
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
 }

void sendXLSX(HttpServletResponse response, byte[] bytes, String name)
        throws IOException
{
    ServletOutputStream stream = null;

    stream = response.getOutputStream();
    response.setContentType(CONTENT_TYPE_XLSX);
    response.addHeader("Content-Type", CONTENT_TYPE_XLSX);
    response.addHeader("Content-Disposition", "inline; filename=" + name);
    response.setContentLength((int) bytes.length);
    stream.write(bytes);
    stream.close();
}

This is invoked by the GWT client in the following manner:

String url = GWT.getModuleBaseURL() + "ExportServlet";
Window.open(url, "", "");

and the user is prompted to download the file. Good, thats what I want :)

But I would like to attach a lot of data in the request, and afaik, there is a limit to how much data you can put in a URL parameter ("ExportServlet?data=..."), so I would like to wrap that in a POST request instead.

I have tried the following from GWT:

String url = GWT.getModuleBaseURL() + "ExportServlet";
RequestBuilder builder = new RequestBuilder(
                            RequestBuilder.POST, url);
Request response = builder.sendRequest("test data", new RequestCallback() 
{
    @Override
    public void onResponseReceived(Request request, Response response)
    {
        System.out.println("");
    }

    @Override
    public void onError(Request request, Throwable exception)
    {
        System.out.println("");
    }
});

and this in my servlet:

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException
{
    try
    {
        String data = req.getReader().readLine();
        byte[] xlsx = createTest(data);
        sendXLSX(resp, xlsx, "test.xlsx");
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}

but the user is not prompted to download the file. The doPost method is invoked and the data is received by the servlet, but am I supposed to extract the XLSX file from the response which I receive in the GWT app? and how am I suppose to do that?

Appreciate any help or comments :)

2 Answers

Hi I have the same issue exactly , and solve it by using directlly call the servlet using Window.Location.replace(URL.encode(servletUrl));

check this link as well related Issue

Related