Assistance required with sending an xlsx-file from the server to the client
This is how it was done BEFORE:
JavaScript (click #export_xls button):
export_xls: function(event) {
window.location = ... + this.workspace.query.id + "/export/xls";
}
Java (creating xls-file using Apache POI API):
@GET
@Produces({"application/vnd.ms-excel" })
@Path("/{queryname}/export/xls/{format}")
public Response getQueryExcelExport(
@PathParam("queryname") String queryName,
@PathParam("format") @DefaultValue("flattened") String format){
// ...
try {
byte[] doc = olapQueryService.getExport(queryName,"xls","flat"); // file
String name = "file.xls";
return Response.ok(doc, MediaType.APPLICATION_OCTET_STREAM).header(
"content-disposition",
"attachment; filename = " + name).header(
"content-length",doc.length).build();
}
catch (Exception e) {
log.error("Cannot get excel for query (" + queryName + ")",e);
return Response.serverError().build();
}
}
It worked well in the past, but now there's a need to transfer data from JavaScript to Java, which will process it and create an xlsx file. This involves using ajax to send the data in JSON format...
export_xls: function(event) {
var data = this.workspace.query.result.lastresult();
var url = ... + this.workspace.query.id + "/testexportxls";
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
async: false,
contentType: "application/json"
});
},
...and then creating the file in Java (similar to the previous method):
@POST
@Produces({"application/vnd.ms-excel" })
@Consumes(MediaType.APPLICATION_JSON)
@Path("/{queryname}/testexportxls")
public Response setQueryExcelExport(final Object jsonData)
{
Workbook wb = MyFileBuilder.getFile(jsonData);
try {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
wb.write(bout);
byte[] doc = bout.toByteArray();
String name = "file.xlsx";
return Response.ok(doc, MediaType.APPLICATION_OCTET_STREAM).header(
"content-disposition",
"attachment; filename = " + name).header(
"content-length",doc.length).build();
}
catch (Exception e){
log.error("Error while xlsx-file creating. Exception message: ",e);
return Response.serverError().build();
}
}
But retrieving the file seems to be problematic now, possibly due to the use of ajax.
Is there a quick solution that requires minimal code changes?
Unfortunately, I have limited knowledge about Response, HttpServletResponse, and similar concepts. Any help would be appreciated.
Thank you for your time.