简体   繁体   中英

How to display stored images in Spring Boot using Angular 4?

I am using Spring Boot and Angular 4. I have uploaded an image to the project location. When I try to view the uploaded image, it is not displayed but an error is thrown. How can I view the image?

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());
    }

在此处输入图片说明

Try updating your mapping in spring boot controller to:

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

this will indicate that the returned object must be handled as a JPEG image.

In Angular create the required path to image and pass is to the img element, eg:

components.ts:

fileUrl = '/getUploadfiles/1';

ang.html:

<img [src]="fileUrl">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM