javascript - 使用 Spring Boot 和 Angular 9 问题检索图像
问题描述
我在使用 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)
有人可以告诉我我做错了什么或什么。
提前感谢。
解决方案
这里有两点需要纠正:
您可能会收到 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
推荐阅读
- python-3.x - 正则表达式检查字符串中是否存在一个或多个特殊字符
- c++ - 如何将变量初始化为附加到播放器的相机组件的指针
- python - 当列不为空时,pandas to_excel 问题给出索引空错误
- c# - 从 WebClient.UploadString 接收数据
- python - 通过 select ... where ... 命令使用 python.connector 时出错
- postgresql - 包含大型活动事务的 WAL 在检查点后是否被回收?
- javascript - 如何生成 2 种颜色,其中一种是另一种的阴影?
- here-maps-rest - 我可以使用地理围栏将形状坐标内的所有道路标记为避让或优惠吗?
- ios - 如何修复命令 PhaseScriptExecution 失败并在 macOS 中运行 Flutter 时出现非零退出代码?
- node.js - TSC 将 node-cron 模块导出为 ["default"] 给 schedule() 未定义