使用 spring 引导和 angular 9 问题检索图像

Retrieve image using spring boot and angular 9 problem

我在使用 api rest 和 spring security jwt 从 spring boot (webapp/images) 获取图像到 angular 9 时遇到问题。 当我保存我的图像时,它工作...我在文件夹 webapp/images 中找到它 但是当我尝试获取图像时,我无法显示它 这是我的代码。

正在保存图片:

 //region Save UserProfile
@PostMapping
public ResponseEntity<?> createUserProfile(@RequestParam("file") MultipartFile file,  @Valid @RequestParam("userProfile") String userProfile)throws Exception{

    boolean isExit = new File(context.getRealPath("/Images/")).exists();
    if (!isExit)
    {
        new File (context.getRealPath("/Images/")).mkdir();
        System.out.println("---Folder Was Created---");
    }
    String filename = file.getOriginalFilename();
    String newFileName = FilenameUtils.getBaseName(filename)+"."+FilenameUtils.getExtension(filename);
    File serverFile = new File (context.getRealPath("/Images/"+File.separator+newFileName));
    try
    {
        System.out.println("Image");
        FileUtils.writeByteArrayToFile(serverFile,file.getBytes());

    }catch(Exception e) {
        e.printStackTrace();
    }

    UserProfile userProfileMapper = new ObjectMapper().readValue(userProfile, UserProfile.class);

    userProfileMapper.setUrlImage(newFileName);
    UserProfile newUserProfile=iCommonService.save(userProfileMapper);
    return new ResponseEntity<>("UserProfile was saved",HttpStatus.CREATED);
}
//endregion

Spring 引导控制器:

//USERPROFILE_IMAGE_BY_USER_UID= "/imageuserprofile/{userprofileuid}"
@GetMapping(path = APIName.USERPROFILE_IMAGE_BY_USER_UID)
public byte[] getPhoto(@PathVariable("userprofileuid") String userprofileuid) throws Exception{
    UserProfile userProfile   = iCommonService.findByUid(userprofileuid);

    if(userProfile == null){
        throw new CommonServiceException("User profile uid not found");
    }
    return Files.readAllBytes(Paths.get(context.getRealPath("/Images/")+userProfile.getUrlImage()));
}

Angular 服务

  private baseUrl = 'http://localhost:8080/userprofile';
  public host :string = "http://localhost:8080";
  
  getUserProfileImage(uid: string): Observable<any> {
    return this.http.get(`${this.baseUrl}/imageuserprofile/${uid}`);
  }

我的组件

constructor(
public userProfileService: UserProfileService,
) {}


getImageUserProfile() {
this.userProfileService
  .getUserProfileImage(this.userProfileUid)
  .subscribe((image) => {
    this.imageUserProfile =image;
  });
}

在我尝试使用的模板中:

<img
      class="profile-user-img img-responsive img-circle"
       [src]= "'data:image/png;base64,'+imageUserProfile"
      alt="User profile picture"
    />

这给我 (data:image/png;base64,undefined:1 GET data:image/png;base64,undefined net::ERR_INVALID_URL)

<img
      class="profile-user-img img-responsive img-circle"
       [src]= "imageUserProfile"
      alt="User profile picture"
    />

这给我(“JSON 位置 0 中的意外标记 �”

我也试试

<img
      class="profile-user-img img-responsive img-circle"
       src= "{{this.userProfileService.host+'/userprofile/imageuserprofile/'+userProfileUid}}"
      alt="User profile picture"
    />

这给我 (GET http://localhost:8080/userprofile/imageuserprofile/2SGI2U8WXUVSfMdgZqhQrok66wLaU03y 403)

有人能告诉我我做错了什么吗?

感谢先进。

这里有两点需要更正:

您可能收到 403 错误,因为您没有传递 http.get() 请求的 headers 中所需的 jwt 身份验证令牌。只有当您共享与 spring 安全性相关的代码时,我才能肯定地说出您已经覆盖默认 spring 启动安全配置以实现您的 jwt 安全性。

您的 http.get() 可能看起来像这样。

private baseUrl = 'http://localhost:8080/userprofile';
  public host :string = "http://localhost:8080";
  
  getUserProfileImage(uid: string): Observable<any> {
    headers:HttpHeaders=new HttpHeaders().set(<jwt header name>,<token value>)
    return this.http.get(`${this.baseUrl}/imageuserprofile/${uid}`,{headers:headers});
  }

关于如何正确处理和显示您收到的图像的第二部分 来自 angular http.get(),这个堆栈答案将帮助你 GET data:image/png;base64,{{image}} net::ERR_INVALID_URL