Wednesday, December 18, 2013

Dojo: Download a file with GET/POST

There is a old trick to use iframe and its src to download a file. The same can be achieved through
dojo.io.iframe.send(xhrArgs)
http://livedocs.dojotoolkit.org/dojo/io/iframe
the dojo.io.iframe.send takes same parameter as xhrGet or xhrPost. And no iframe component is required!

sample

xhrArgs = {
  url: "service endpoint",
  form: "formid",
  content: ""
}

<form method="POST" id="formid" />

The formid is dummy and is required (workaround) in this case to make a POST call else it makes a GET call.

Content sent is of type application/x-www-form-urlencoded. Make sure the service takes care of this.

xhrArgs = {
  url: "service endpoint",
  form: "formid",
  content: { data: dojo.toJson({name: "Amod", location: "Bangalore" }) }
}

The same should be handled in a JAX-WS call through

@POST
@Produces("application/vnd.ms-excel")
@Consumes({MediaType.APPLICATION_FORM_URLENCODED})
method(@FormParam("data") String data, ..) {
       MyRequestObject reqObj = new ObjectMapper().readValue(data, MyRequestObject.class);
       ...
       ...
       ResponseBuilder responseBuilder = Response.ok(file);
       responseBuilder.header("Content-Disposition", "attachment; filename=<filename to appear in download>");
       return responseBuilder.build();
}


No comments: