Ser Yoga
Ser Yoga

Reputation: 466

Download file using Jersey and RestyGWT

hi is it possible to download a file from a server with passing a List as a Parameter

with RestyGWT and Jersey 1.7?

On the server side i have the following web service

@POST
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@Path("/download")
public Response downloadFiles(@Context HttpServletResponse response, List<FileInfo> files) {
    ZipFile zip = null;

    String uuid = UUID.randomUUID().toString();
    response.setHeader("Content-Disposition", "attachment; filename="
            + uuid + ".zip");
    try {
        zip = new ZipFile(response.getOutputStream());
        File f = new File(ConfigurationLoader.getRealPath("/logo.png"));
        zip.addFile(f, "");
        zip.getOutputStream().flush();
        zip.getOutputStream().close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

when i type in the browser localhost:8080/Url/download it works but how can i download the file with Resty Gwt or via Window.open()?

i want to use POST not GET so i can pass a list of serializable object e.g: List files.

i tried on the client side with RestyGWT:

@POST
@Produces("application/zip")
@Path("/download")
public void downloadFiles(List<FileInfo> files, MethodCallback<Response> response);

private static final Resource resource = new Resource(
                GWT.getHostPageBaseURL() + "rest/files");

        public static final FileRestService get() {
            if (instance == null) {
                instance = GWT.create(FileRestService.class);
                ((RestServiceProxy) instance).setResource(resource);
            }
            return instance;
        }

but it doesnt work and i cant find examples about downloading files in restygwt

Upvotes: 1

Views: 1305

Answers (1)

In general(*) you cannot use ajax to download files, so you have to use a Window.open() or an iframe to ask the user to save the file as.

Take a look to my response in this query: Window.open in GWT not open correctly with in a call back function

Of course using iframes you cannot use POST, but you could code a loop to ask for a different file each time the last iframe is loaded. The user will be asked as many times as files to download.

You could use a FormPanel though, then add some hidden parameters and POST it to the server. FormPanel displays the response in a hidden iframe, so setting the appropriate headers (content-type content-disposition) you could download a file and ask the user to save as. I would zip the set of files so the user can save or open the content since more OS have utilities to visualize compressed files.

(*) using XHR you could download files, but you need a way to process the content and display it to the user. It's normally used for text files html, txt, xml, etc. Take a look to the html5 api to receive and process binary data. You cannot create files in the user's filesystem though.

Upvotes: 2

Related Questions