【发布时间】: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