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

Is it possible for a component to have multiple templates that can be switched based on a parameter?

Scenario My task is to develop a component that fetches content from a database and displays it on the page. There needs to be two components working together to create a single page, following a specific component tree structure. DataList - receives ful ...

Creating a Word document from a template using Content Control Data Binding with OpenDoPE explained

I have a template in Word with specific fonts, colors, and elements. I am retrieving data from a database into a POJO and now want to extract relevant information from this POJO to create a Word document based on my template's specifications. This do ...

Step-by-step guide on adding a command to a submenu through the vscode extension api

I'm developing a Visual Studio Code extension and I want to include a command in a submenu like this https://i.stack.imgur.com/VOikx.png In this scenario, the "Peek" submenu contains commands such as "Peek Call Hierarchy". My current Package.json fi ...

Are you experimenting with a web application by utilizing jUnit or another API?

Is it feasible to develop a testing suite for evaluating a web application with the junit API without incorporating additional APIs or considering alternative options? Can this also handle ajax, jquery, and javascript components? In other words, will I b ...

The floating filter in ag-Grid for Angular features a dropdown menu styled with Bootstrap

In my ag-grid table, I have a Bootstrap dropDownMenu displayed in CELL and in FLOATING FILTER. The issue arises when the dropdown menu is triggered - it gets hidden in the cell, as shown in the picture. https://i.sstatic.net/xBsPf.png To fix this proble ...

Disabling the ESC key from clearing input fields in Bootstrap-5: A step-by-step guide

I have come across this code snippet for a search field: <form class="container" role="search"> <div class="row"> <div class="col-12"> <input name="searchItem" #search ...

Is Webpack CLI causing issues when trying to run it on a .ts file without giving any error

I am facing an issue with my webpack.config.js file that has a default entrypoint specified. Here is the snippet of the configuration: module.exports = { entry: { main: path.resolve('./src/main.ts'), }, module: { rules: [ { ...

Using Angular2: Implementing a single module across multiple modules

Let's delve into an example using the ng2-translate plugin. I have a main module called AppModule, along with child modules named TopPanelModule and PagesModule. The ng2-translate is configured for the AppModule. @NgModule({ imports: [TranslateMo ...

Utilizing React with Typescript to create JSX text translation files

My task involves translating text stored in a file... ///translations.txt const TEXT: { [x: string]: { [y: string]: string } } = { en: { joinNow: <React.Fragment>Join <b>Now<b/></React.Fragment>, signUp: <React.Fragmen ...

Ensuring that Selenium WebDriver effectively waits for intricate webpages with extensive JavaScript to fully load

Working with Selenium to test a web application that utilizes a significant amount of JavaScript during page load can present challenges. Unfortunately, in the event of poorly written JavaScript code that cannot be modified, waiting for an element using th ...

Using TypeScript to filter and compare two arrays based on a specific condition

Can someone help me with filtering certain attributes using another array? If a condition is met, I would like to return other attributes. Here's an example: Array1 = [{offenceCode: 'JLN14', offenceDesc:'Speeding'}] Array2 = [{id ...

typescript class that utilizes a function with multiple shapes (overloading) and generics

TYPESCRIPT playground Is there a concept similar to Overloads for classes? I encountered an issue with the creation of createRequest.ts and the function should be error-free. I am looking to apply the same generics used in the createRequest function to th ...

Exploring the capabilities of SparkSql with regular expressions

When working with JavaSparkSQL, I often utilize a dataset that is derived from a JSON file containing key-value pairs. When querying the dataset to view specific values, I typically write something along the lines of: SELECT key1.name from table Here&ap ...

What is the best way to execute a series of Cucumber Feature files consecutively, all while using the same browser window?

My goal is to run multiple test cases consecutively in the same web browser without having to close and reopen the window each time. This would eliminate the need to repeat login steps for each test case. I am currently working on automating test cases us ...

Tips for integrating Excel files with NestJS

I'm in the process of developing a REST API that will utilize a third-party API to retrieve specific status information. The URLs needed for this API are stored in an Excel file, which is a requirement for this use case. My goal is to extract the URLs ...

Updating text inputs in Angular can be done more efficiently using Angular Update

I need to make adjustments to an Angular application so that it can run smoothly on older machines. Is there a more efficient method for updating a text input field without using (keyup) to update after each keystroke? I haven't been able to find any ...

What are the steps for customizing the interface in TypeScript?

After fixing a type error related to adding custom functions to the gun chain by including bind():any within IGunChainReference in @types/gun/index.ts, I am wondering how to transfer this modification to one of my project files. I have not been able to fi ...

The service functions are being called two times consecutively

I am utilizing an authentication component @Component({ selector: "oe-authentication-view", templateUrl: "./authentication-view.component.html" }) export class AuthenticationViewComponent implements OnInit { authorizationFormGroup: FormGroup; ...

Creating a dynamic list from an array of strings in Angular: A step-by-step guide

Within my .ts component file, I have declared a variable called campaignList as an array of strings. campaignList: string[] I am dynamically populating this list programmatically. In the corresponding HTML file, I have set up a table structure with heade ...

Incorporate the Angular router within markdown hyperlinks

When utilizing ngx-markdown to display my FAQ, I include links to both external resources (beginning with http) and internal content (starting with /). I am interested in passing the Angular router to my markedOptionsFactory so that I can easily navigate ...