【问题标题】:Retrieve image using spring boot and angular 9 problem使用 Spring Boot 和 Angular 9 问题检索图像
【发布时间】:2020-11-08 18:43:15
【问题描述】:

我在使用 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

弹簧启动控制器:

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

角度服务

  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"
    />

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

我也试试

<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)

可以告诉我我做错了什么或什么。

谢谢你。

【问题讨论】:

    标签: javascript java spring-boot spring-security angular9


    【解决方案1】:

    这里有两点需要纠正:

    您可能会收到 403 错误,因为您没有传递 http.get() 请求标头中所需的 jwt 身份验证令牌。只有当您共享与 Spring Security 相关的代码时,我才能肯定地说,您已经覆盖了默认的 Spring Boot 安全配置以实现您的 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

    【讨论】:

      猜你喜欢
      • 2021-06-03
      • 2018-10-30
      • 2019-04-02
      • 2020-09-08
      • 2019-01-24
      • 1970-01-01
      • 2016-12-01
      • 2020-07-19
      • 1970-01-01
      相关资源
      最近更新 更多