【问题标题】:How to display stored images in Spring Boot using Angular 4?如何使用 Angular 4 在 Spring Boot 中显示存储的图像?
【发布时间】:2018-07-22 12:46:27
【问题描述】:

我正在使用 Spring Boot 和 Angular 4。 我已将图像上传到项目位置。 当我尝试查看上传的图像时,它没有显示,但会引发错误。 如何查看图片?

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 控制器:

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

【问题讨论】:

    标签: java angular typescript spring-boot


    【解决方案1】:

    尝试将 spring boot 控制器中的映射更新为:

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

    这将表明返回的对象必须作为 JPEG 图像处理。

    在 Angular 中创建所需的图像路径并传递给 img 元素,例如:

    components.ts:

    fileUrl = '/getUploadfiles/1';
    

    ang.html:

    <img [src]="fileUrl">
    

    【讨论】:

    • 嘿,非常感谢
    猜你喜欢
    • 1970-01-01
    • 2019-07-04
    • 1970-01-01
    • 2021-11-02
    • 1970-01-01
    • 2018-04-14
    • 1970-01-01
    • 2018-01-05
    • 2018-02-15
    相关资源
    最近更新 更多