Tips for showcasing saved images in Spring Boot with Angular 4

I am currently utilizing Spring Boot in combination with Angular 4. The issue I am facing involves uploading an image to the project location. However, upon attempting to view the uploaded image, it does not display correctly and instead throws an error. How can I go about fixing this problem?

ang.html:

<button type="button" class="button btn-info" 
                            (click)='showInfo()'>ShowImages</button>
                <div class="panel panel-primary">
                    <div class="panel-heading">List of Images</div>
                    <img [src]="fileUploads">
                </div>

components.ts:

fileUploads: any;
  sid: number = 1;
  showInfo() {   
    this.drugservice.getFiles(this.sid).subscribe(data => {this.fileUploads = data, alert(data)}), err => {
      console.log('Error Occured showInfo');
    };
  }

service.ts

getFiles(id: number): any {
  return this.http.get(this.getFileuploadedURL+'/'+id, { responseType: ResponseContentType.Blob }).map(
  (res) => {
      return new Blob([res.blob()], { type: 'image/png' })
  });
}

springBoot Controller:

@GetMapping(value = "/getUploadfiles/{id}")
    @ResponseBody
    public byte[] getImage(@PathVariable Integer id) throws IOException {
        String filename = "01";
        System.out.println("id : " + id);
        File serverFile = new File(rootLocation + "\\" + filename + ".jpg");
        System.out.println("serverFile : " + serverFile);        
        return Files.readAllBytes(serverFile.toPath());
    }

https://i.stack.imgur.com/TjtQt.png

Answer №1

To enhance your mapping in the spring boot controller, consider updating it to:

@GetMapping(value = "/getUploadfiles/{id}", produces = MediaType.IMAGE_JPEG_VALUE)

This specification will ensure that the returned object is treated as a JPEG image.

When working with Angular, construct the necessary path for the image and assign it to the img element, for example:

components.ts:

fileUrl = '/getUploadfiles/1';

ang.html:

<img [src]="fileUrl">

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

An effective method for targeting a specific button within a CSS file

I have multiple button tags in my code, but I need to style a specific one using CSS. How can I target this particular button and apply styles only to it while leaving the others unchanged? Do I need to assign the button to a variable and reference that va ...

Having trouble executing the project using Gulp

I'm a beginner in front-end development and I am working on an existing project that I'm having trouble running. According to the documentation, I should run the project by executing: $ gulp && gulp serve But I keep getting this error: ...

Navigating user profile routes effectively involves understanding the structure of the application

I'm currently working on developing a user-list feature that will display all users, along with user-detail components for each individual user. My main goal is to restrict access so that only administrators can see the complete list of users, while ...

What is the process of sending JSON parameters in an Android web service request?

Possible Duplicate: How to send a JSON object over Request with Android? Being new to Android development, I encountered an issue when trying to send requests to a web service in JSON format. After researching online, I came across this code snippet f ...

Encountered an issue when deploying on CF: "ERROR The serve command must be executed within an Angular project, however a project definition could not be located."

I need to set up my Angular Application on Cloud-Foundry. Here is the package.json file currently located in the dist folder: { "name": "showroom-app", "version": "0.0.0", "engines": { "node" ...

Trigger a function upon a user's departure from a page or route in Angular 2

Is there a way to trigger a function only when the current route changes away from a specific component, such as when navigating away from "..../user/user-details"? I want this method to execute regardless of whether the route is changed through user inter ...

Angular 17 isn't notifying child component of signal changes

In the statistics module, I have a signal that specifies the type of charts to display and this signal is updated through a radio button group. The signal: typeSignal = signal<string>('OIA') The radio buttons for setting the : <div clas ...

Can models drive reactive forms by automatically mapping them to FormGroups?

Is it possible to automatically generate a FormGroup from a Model? If I have a Model with multiple Properties: Model: Person firstName: string, lastName: string, street: string, country: string .... And I would like to create a basic FormGroup based on ...

Every time I attempt to submit the login form on the Ionic and Angular page, instead of capturing the values of the form group, the page simply refreshes

Struggling with submitting the login form in Ionic and Angular? When attempting to submit, the page reloads instead of capturing the form group values. I am utilizing angular reactive forms and form builder within the ionic framework. Need assistance in id ...

Get the latest B2B department for the client within Spartacus

How can I display the current B2B Unit name in the header for the customer? I have been exploring ways to retrieve the B2B Unit for the current customer and found that there is a payload available for the /current? endpoint that loads on the initial page ...

Exploring the world of third-party APIs

I am currently working on fetching data from an external API and displaying it. In order to enhance flexibility, I am aiming to completely separate the API integration from my code and use custom-defined data structures instead. Here is a brief visual ov ...

Leveraging angular-cli built files as a dependency for another angular2 project

Is it feasible to utilize the build artifacts from one angular-cli project in another? For instance, I have created and published project "A", then subsequently created project "B" and added A to its dependencies (node_modules). Currently, these are the ...

Simulate a complete class with its constructor, instance methods, and static functions

I have been searching for a comprehensive example that demonstrates how to properly mock all three elements (ClassA constructor, ClassA.func1 instance function, and ClassA.func2 static function) in my TypeScript project. In the code under test, I need to v ...

Required Field Validation - Ensuring a Field is Mandatory Based on Property Length Exceeding 0

When dealing with a form that includes lists of countries and provinces, there are specific rules to follow: The country field/select must be filled out (required). If a user selects a country that has provinces, an API call will fetch the list of provinc ...

Stop MatDialog instance from destroying

In my application, I have a button that triggers the opening of a component in MatDialog. This component makes API calls and is destroyed when the MatDialog is closed. However, each time I open the MatDialog for the second time by clicking the button agai ...

Advanced filtering of arrays in JavaScript

The data structure I am working with consists of nested arrays of objects, each containing further nested arrays ad infinitum. Imagine deep nesting levels. Let me illustrate my goal with an example. I have a collection of groups. Each group contains heroe ...

Creating efficient React components with TypeScript and leveraging generic props

I’ve been working on understanding and resolving my issue with React components' generic props. I came across a code example in an article about using TypeScript with functional React components and generic props. Unfortunately, when trying to repli ...

Tips for accessing a RouterState from the @ngxs/router-plugin before and during the initialization of other states

Previously, in an Angular 8.0.0 and 3.5.0 NGXS application, I successfully retrieved the RouterState using SelectSnapshot from the @ngxs/router-plugin within other states before component rendering. However, in my latest application, the RouterState now re ...

How can you inform TypeScript about a file that will be included using a script tag?

I am currently utilizing TypeScript for my front-end JavaScript development, and I have a situation where I am loading two scripts from my index.html file as shown below: <script src="replacements.js"></script> <script src="socket.js">&l ...

Enable the parsing of special characters in Angular from a URL

Here is a URL with special characters: http://localhost:4200/auth/verify-checking/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="59663c34383035643230383d2b606a6e6b686d6e6e193e34383035773a3634">[email protected]</a> ...