I have a piece of code that allows me to download a zip file using JavaScript and AJAX. On the back-end, I utilize REST resources and Java to process the request. Below is the JavaScript code for downloading the file.
var urlDownload = "/test/download/";
$.ajax({
url: urlDownload ,
async:true,
type: 'GET',
success: function (data) {
if (data != undefined) {
window.location = urlDownload;
}
},
error : function(xhr, textStatus, exception) {
// display the error message
return true;
},
cache: false
});
}
Here is the corresponding JAVA-REST code responsible for handling the user interface's request.
@Metric(op = "get the file")
@Path("/test/download/")
@GET
@Produces("application/zip")
public Response downloadZIP() {
System.out.println("Downloading the zip file");
try{
Logic to create the zip file and return the FILE object
ResponseBuilder response = Response.ok((Object) file);
response.header("Content-Disposition",
"attachment; filename=test.zip");
return response.build();
} catch (Exception e) {
// return an error message
}
}
The issue lies in the fact that the print statement is being executed twice, meaning my business logic for creating the zip file is also running twice. After some debugging, I discovered that by commenting out window.location = urlDownload; in the JavaScript code, the execution only happens once, but the file does not get downloaded because the necessary JS code is commented out.
This raises the question: why is the REST resource executing twice?
Could it be because the GET and Download URLs are identical, causing them to map to the same resource when a request comes from the UI?
Is there a way to bypass this besides creating two different REST resources with distinct URLs – one for processing the GET request with all the necessary logic, and another specifically for handling the download after the first resource has been executed? Alternatively, is there another method to download files using JS or AJAX instead?