The JAVA REST Resource is being triggered twice when downloading a file

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?

Answer №1

Using window.location = urlDownload; in JavaScript is the method to dynamically load a new page in the browser. Essentially, you are initiating a request to your web service (initial call), followed by directing the browser to the URL of the web service, triggering a second call to display the requested content as a webpage.

Answer №2

When AJAX GET is used, it automatically triggers the download code without the need for window.location = urlDownload. This raises questions about the necessity of AJAX in this scenario - have you tested if the download code still gets called without using window.location = urlDownload?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implement a jSlider in Java to adjust the audio output volume

I currently have a class that manages the playback functions for MP3 files such as play, pause, and stop. Is there a way to adjust the volume using javax.sound.*? Or do I need to include a separate method for controlling the volume within the existing M ...

What is the correct way to handle a rollback in functions using transactions annotation when the save operation results in a null return value?

In my project, I utilize Spring Boot 5 alongside MongoDB. One requirement is to save user information in the users collection and also save the user's authority in a separate collection simultaneously. If an error occurs during the saving process and ...

Issue with Bootstrap 3 dropdown not receiving updates

My goal is to dynamically populate a bootstrap 3 dropdown menu from a MySQL database. Everything works perfectly the first time I load the data. However, when I add more rows to the database, they do not automatically show up in the dropdown. Only after ...

Is there a way to delay rendering the html until all the content has been fully downloaded?

Whenever I visit my webpage, I notice that the content starts loading without the animation applied to it. It seems like the CSS hasn't finished downloading yet. To solve this issue, I added a preloading bar overlay to signal that the content is still ...

"Sending data from a web page to a server-side script using AJAX: A step

I am struggling to pass a variable from the view file to the include_player_id in the controller file using AJAX in order to execute a function. This has been quite challenging for me so far. If someone could assist me with this, it would be greatly appre ...

Change integer time to String time exclusively, excluding Date

Let's say I have a particular integer: int i = 110631; Now, I need to transform this integer into a time format like "11:06:31". Initially, I attempted to do this using a SimpleDateFormat: SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm: ...

Look for a regular expression that matches numbers ranging from 1 to 31, either with or without a leading

I am in the process of setting up validation on an <input> element to prevent the user from inputting incorrect characters. Currently, I am utilizing ng-pattern for this purpose, which successfully restricts the user from entering invalid characters. ...

There appears to be a snag with PL SQL on Java

In the code snippet provided, there seems to be an issue with its functionality. CallableStatement cs = dbc.prepareCall("" + "DECLARE " + "transno numeric (9,0); " + "jobno numeric (9,0); " + ...

Create a dataset in Spark by utilizing an encoder to store rows as an array type

I need help understanding the correct way to implement an encoder to create a Dataset from the RDD provided below: For example: JavaRDD<Integer[]>rdd= sparkContext.parallelize( Arrays.asList(new Integer[][]{new Integer[]{1,2}, ...

Submitting a form in PHP without refreshing the page

I am facing an issue with posting my form to Mysql without refreshing the page. I have tried looking for solutions online, but nothing seems to work. Can anyone assist me with this? <script> $('#submit').click(function() { $.ajax({ ...

show a loading animated image in a particular div during the process of loading data using ajax

Is it possible to modify the code below to only display the loading gif within the div-Summary-Report, rather than for the entire page? <div class="row"> <div class="col-lg-12 div-Detailed-Report"> //some content </div> < ...

Android code for displaying images

What is the best way to retrieve and showcase photos stored in the internal storage of your mobile device? ...

Improve efficiency by automating ajax requests using HTML5 data- attributes

Imagine having a form like this: <form> ... <input type="submit" /> </form> You want the form to be submitted normally, but if the user has javascript enabled, you need it to be submitted using javascript ($.ajax). Dealing with ...

Regularly send requests to an Express server using the $.get function

Operating an Express server with a time generator to send generated time data to the client page gtm.hbs. How can I implement regular polling of the server from the client using Ajax? Displayed below is the server-side code located in \routes\ge ...

What is the procedure for ordering weekdays starting from Sunday (0) and including incomplete weeks?

When retrieving opening hours for libraries from a database, the data returned looks something like this: { "5":{ // library ID "4":{ // interval ID "statement":"", "start_date":"5th Jan 2015", "end_date":"1st Mar 2015" ...

Encountering an issue with parsing JSON using Retrofit and GSON, faced errors while attempting to parse and retrieve callback data

I am utilizing Retrofit to manage Calls to my API for an Android Application. My goal is to have Retrofit handle the parsing of JSON and create a list of Objects based on the POJO I developed. The error message I encountered is "com.google.gson.JsonSyntax ...

Lookup all users in the database using search criteria in MongoDB

Currently, I am attempting to search for a user based on their name field using insomnia for testing purposes. In my schema for users, it looks like this: const userSchema = mongoose.Schema({ id: { type: String }, name: { type: String, require ...

html elements correspond directly to individual json objects

Looking for a precise way in javascript/jquery to connect objects created in an external JSON file to populate their respective HTML divs. The code snippet and JSON data are provided below, along with an image for reference that shows the layout of the div ...

Guide on populating a series of rectangles in a line based on values stored in an array using d3.js

I have 100 rectangles arranged in a 10x10 square. My goal is to assign colors to the rectangles based on values from an array var avg = [1, 4, 4, 7, 11, 15, 58] I'm facing an issue at the value 4 being repeated and I find the current code quite mess ...

Create intricate patterns within specified boundaries

I've been encountering an issue involving drawing and integrating meshes into the scene within THREE.JS. I'm curious about how I can insert objects specifically in the 'X' region rather than the 'Y' area? https://i.sstatic.ne ...