Handling the http.get response in a Java Spring method

I am faced with managing the HTTP GET response from a Java Spring GET request. The file downloaded from the server is in zip format, containing a .pdf and .png file. Below is the Java code snippet:

@RequestMapping(value="/data/{meetingId}", method = RequestMethod.GET)
public byte[] getMeetingRest(@PathVariable(value="meetingId") String meetingId) {
    byte[] file = new byte[1024];
    Buffer buf =null;
    try {

        String url = getContentServer()+"/data?username="+getUsername()+"&password="+getPassword()+"&id="+meetingId;
        RestTemplate templ = new RestTemplate();
        file = templ.getForObject(url, byte[].class);

    } catch (Exception e) {
        String msg = "Error retrieving meeting list";
        logger.error(msg, e);
    }
    logger.info("file zip  --> "+file.length);
    return file;
}

And this is the Angular HTTP GET request:

 appControllers.controller('FolderListController', ['$scope', '$routeParams', '$http', '$timeout', '$q', 'global',
                                                   function($scope, $routeParams, $http, $timeout, $q, global){
    console.log("FolderListController");
    var meetingId = $routeParams.meetingId;

    $http.get(CONTEXT_PATH+"/services/data/"+meetingId, {responseType: 'arraybuffer'})
    .success(function(data){
        console.log(data.length);
        console.log(data);
    })
    .error(function(e){
        console.log("Errore chiamate rest data zip   e = "+e);
    });

    //Displaying the correct items.
    for(var i=0;i<global.meetings.length;i++){
        console.log("meetingList["+i+"] = "+global.meetings[i]);
        if(global.meetings[i].id == meetingId){
            console.log("Found id :  id="+global.meetings[i].id+"  --  meetingId  = "+meetingId);
            $scope.items = global.meetings[i];
            break;
        }
    }
}]);

The output is as follows:

undefined controllers.js:108 ArrayBuffer {}.

Any helpful advice or suggestions would be greatly appreciated. Thank you.

Answer №1

To achieve the desired result, consider utilizing the @ResponseBody annotation in your code snippet or switch from using the @Controller annotation to @RestController.

@Controller
....
@RequestMapping(value="/info/{eventId}", method = RequestMethod.GET)
public @ResponseBody byte[] getEventRest(@PathVariable String eventId) {
    ...
}

Alternatively:

@RestController
...
@GetMapping("/info/{eventId}")
public byte[] getEventRest(@PathVariable String eventId) {
    ...
}

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

Issue encountered: Failure to locate module 'socket.io' while attempting to execute a basic server JavaScript file

Below is my server.js file that I am attempting to run using node server.js: var app = require('express')(); var http = require('http').createServer(app); var io = require('socket-io')(http); //also tried socket.io instead of ...

Is there a way to trigger the onclick event while dragging the div?

Exploring a Div: <div id="up" onmousedown="handleMouseDown('url(/scanToUserBox/img/cpt_subfunc_005_prev_p.png)', this)" onclick="changePage('up')"> </div> Upon clicking the div, the onmousedown event is trig ...

`Loading CSS and JS files in node.js: A step-by-step guide`

I've searched through numerous similar questions without success, so I'm reaching out for help. My folder structure looks like this: Source Code Frontend Graphs.html Graphs.css Temperature.js Server_Backend server.js I aim ...

Creating distinct identifiers for table cells utilizing the map function

Is there a way to assign a unique id to each MenuItem using the map() function nested within another one? <table className={classes.table}> <thead> <tr> <td /> {sit.sit.map(sit => ( <td className={ ...

PHP scheduler alternative

I have a PHP script called updater.php that performs a task for 1-2 minutes. It is crucial for the script to complete its job. While I can schedule it with cron, I have come up with an alternative solution. The script should only run at specific times wh ...

"The interplay of Vue components: exploring the relationships, lifecycle hooks

Brand new to utilizing Vue.js. I am exploring the concept of having a single parent component and two child components that need to communicate asynchronously through Vue's event bus system. This involves using a dummy Vue object as a shared container ...

How can Angular2 detect when an entity is clicked within a window?

There are multiple items generated using *ngFor: <my-item *ngFor="let item of myArray" [p]="item"></my-item> I am able to handle a click event like this: <my-item ... (click)="doWork(item)"></my-item> However, I want to avoid a ...

Dynamically created HTML elements have no events attached to them in Angular and jQuery

Utilizing jQuery, I am dynamically generating new elements within an Angular Form that has been constructed using a Template Driven Forms approach. Despite successfully creating the dynamic elements, they do not seem to be assigned events/callbacks due to ...

The "Overall Quantity" of items will vary as it goes through different numerical values, despite the fact that I employed --

I am currently working on an e-commerce website with a shopping cart feature. The cart displays the number of items added to it, which increases by one when 'Add to Cart' is clicked and decreases by one when 'Remove' is clicked. However ...

Tips on transforming JSON output into an array with JavaScript

Looking for a solution to convert a Json response into an array using JavaScript. I currently have the following json response: ["simmakkal madurai","goripalayam madurai"]. I need to transform these results into an array format. Any suggestions on how I ...

Setting up Webpack and Babel for ReactJS development

Recently, I started delving into the world of ReactJS and stumbled upon a tool called webpack which acts as a module bundler. However, I've hit a roadblock while configuring it and keep encountering the following error message: ERROR in ./src/index. ...

Using Express.js and Angular for user authentication and session management

In my current project, I am utilizing expressjs and angularjs to create an app. The setup involves expressjs serving a single .html file that houses an angular single-page-application. All routing is handled by angularjs, while expressjs provides web servi ...

Saving extra parameters with MongooseJS

When saving data in my app using a POST query, how can I include additional parameters to the Item? For example, I would like to add user: req.user._id. var Item = new Model(req.body); Item.save(function (err, model) { res.send(model); }); ...

How can I extract the text within an element based on the position of the

In my current project, I have incorporated the incredibly useful jQuery TextRange plugin. Within a highlight div positioned above a textarea element, it is crucial for me to identify the specific element that the user is currently editing. To better illust ...

Adjust the class of the iframe element when clicked

I am attempting to change the class of an iframe (soundcloud embedded track) when it is clicked, in order to apply different properties. However, my code doesn't seem to be working as expected. Here is what I have: Here is a snippet from my index.htm ...

Stop the removal of the CSS content property

When a user enters and re-enters their password, I have a form that checks the strength of the password and displays text accordingly. However, I noticed that if a user makes a mistake and uses the backspace to re-enter the password, the text from data-tex ...

Troubleshooting problem with Angular 2 in Internet Explorer related to the use of [style]="

I've encountered a challenge while using angular 2 (2.0.0-beta.17). The app works perfectly on most browsers, but as expected, IE 11 is causing trouble. The scripts included in the head for angular are: <script type='text/javascript' sr ...

Rendering nested rows in Angular datatables

How can nested tables be better displayed in angular-datatables? One solution involves using rowCallback and setting up click events: $scope.dtOptions = DTOptionsBuilder.fromSource('data.json') .withOption('rowCallback', rowCallbac ...

Having a single quote within a double quote can cause issues with JavaScript code

I am currently developing a Django web app and facing an issue with sending a JSON object to my JavaScript code using a Django template variable. # views.py import json def get_autocomplete_cache(): autocomplete_list = ["test1", "test2", "test3", "te ...

Finding the data type based on the button clicked with javascript: A beginner's guide

I am trying to work with a PHP function that generates dynamically created divisions. Each of these divisions contains a different data type and a button. How can I extract the data type of a division when the user clicks on the submit button using JavaScr ...