照片没有上传,因为在数据库中,如何覆盖?



我是Java新手,但我正在编写的web应用程序的背面是Java的,我的团队中没有人能帮助我。

我的问题是:在用户配置文件组件中,我有一个编辑照片的输入,但每次它都会返回一条错误消息。

这似乎是因为数据库中已经存在文件,所以照片永远不会更新。

我认为后面有什么东西不对劲或不对劲。

前部(角度(

专家配置文件.component.html

<!-- [...] -->
<!-----------------------------------------
img profile
-------------------------------------------->
<div
class="profileImg"
[ngStyle]="{ 'background-image': 'url(' + photoUrl + ')' }"
*ngIf="this.userInfos"
>
<!-- upload or change profile photo -->
<input
type="file"
accept="image/*"
style="display: none;"
#file
(change)="changeProfilePhoto($event.target.files)"
/>
<mat-icon
class="editIcon"
*ngIf="ownProfile"
(click)="file.click()"
matTooltip="Only .png or .jpg/.jpeg img with min-size: Ko and max-size: Ko"
>
edit
</mat-icon>
</div>
<!-- [...] -->

专家配置文件.组件.ts


// imports...
@Component({
selector: 'app-expert-profile',
templateUrl: './expert-profile.component.html',
styleUrls: ['./expert-profile.component.less'],
})
export class ExpertProfileComponent implements OnInit {
//[...]
async changeProfilePhoto(file: FileList) {
console.log(' async changeProfilePhoto....', file);
console.log('---------------------REQUEST------------------------------');
this.fileService
.uploadProfilePhoto(file[0], this.profileId)
.subscribe((res) => {
console.log('changeProfilePhoto (res)', res); // test res= null
if (res == null) {
this.snackbar.open('Error (to handle) : File already uploaded', '', {
duration: 2500,
});
} else {
console.log('loading ok');
location.reload();
}
});
console.log('------------------------ END ---------------------------');
}
}

console.log return--->

[...]
------------------------ END ---------------------------
changeProfilePhoto (res) null

浏览器返回--->带信息的小吃条:

错误(待处理(:文件已上传

照片已上载但未使用。

后端

FileUploadController.java

/* uploadprofilephoto #1 */
@PostMapping("/user/{userId}/avatar")
public ResponseEntity<UserInfo> uploadProfilePhoto(@PathVariable UUID userId, @RequestParam MultipartFile avatar,
HttpServletRequest request) throws IOException {
System.out.println("............................................................................");
System.out.println("                       uploadprofilephoto #1    ");
System.out.println("............................................................................");                                          
try {
System.out.println("............................     TRY     ......................................");

UserInfo u = storageService.addUserAvatar(userId, avatar.getOriginalFilename(), avatar.getInputStream());
URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{userId}").buildAndExpand("").toUri();
return ResponseEntity.created(location).body(u);
} catch(Exception e) {
System.out.println(".......................................   CATCH: (e below)   .....................................");
System.out.println(e);
System.out.println("............................................................................");
return ResponseEntity.ok().body(null);
}

}

FileStorageService.java中的addUserAvatar((

/* #uploadprofilephoto #2*/
public UserInfo addUserAvatar(UUID userId, String filename, InputStream fileContent) {
System.out.println("---------------------------------------------------- ");
System.out.println("                        #2 - change my profile img by    "+filename);
System.out.println("---------------------------------------------------- ");
UserEntity user = userServiceActions.findById(userId);
//If fileId in userProfile is already present in filedatabase , it delete it in filedatabase + directory
//#3
try {
this.delete(user.getImage());
} catch(Exception e) {}
//create path for a new avatar + directory to store it
Path directory = router.getOrCreatePathFromFilename(userId, filename, "avatar");
Path location = fileSaver.store(filename, fileContent, directory);
//request for a new file
var f = new FileRequest();
f.filename = filename;
f.projectId = Optional.of(userId);
MediaType mediaType = MediaType.parseMediaType(getContentType(location));

//Create an entity for this file with a uniq Id, and add it in file db
//#4 + #5
FileEntity fileEntity = fileServiceActions.add(UUID.randomUUID(), mediaType.getType(), mediaType.getSubtype(), f , "avatar");

//update the imageId in user db with the new one
//#6
user.setImage(fileEntity.getId());
System.out.println("---------------------------------------------------- ");
System.out.println("                        #6 - CrudRepository save in user the new imageId:   "+user.getImage());
System.out.println("---------------------------------------------------- ");
userRepository.save(user);//seems to block if a photo was allready uploaded by past with the same filename

//return the new data and update profile
UserInfo userInfo = mapper.map(user, UserInfo.class);
return userInfo;
}

(见下文控制台打印返回(

FileStorageService.java中的delete(((一切似乎都很好(

/* #uploadprofilephoto #3*/
public void delete(UUID id) throws ResourceNotFoundException {
System.out.println("---------------------------------------------------- ");
System.out.println("                        #3 - delete    "+id);
System.out.println("---------------------------------------------------- ");
FileEntity file = fileServiceActions.findById(id);
Path directory = router.getOrCreatePathFromFilename(file.getProjectId(), file.getFilename(), file.getCategory());

fileSaver.deleteFromDisk(directory, file.getFilename());

fileServiceActions.delete(id);
System.out.println("end delete ---------------------------------------------------- ");
}

add((&java中的save(((根据我的说法,Pb来自save(

/**
* #uploadprofilephoto #4
* Allows to give a pre-generated UUID to the file. Useful when we want to have the
* UUID before adding a record to the database.
*/
public FileEntity add(UUID fileId, String type, String subtype, FileRequest req , String category) {
FileEntity fileEntity;

try {
ProjectEntity proj = null;
proj = projectServiceActions.findById(req.projectId.orElseThrow());
fileEntity = toEntity(proj.getId(), req, type, subtype, category);
} catch(Exception e) {
UserEntity user = null;
user = userServiceActions.findById(req.projectId.orElseThrow());
fileEntity = toEntity(user.getId(), req, type, subtype, category);
}
fileEntity.setId(fileId);
System.out.println("----------------------------------------------------");
System.out.println("                        #4 add this new file in file db    ");
System.out.println(fileEntity);
System.out.println("----------------------------------------------------");
return save(fileEntity).orElseThrow();
}
[...]
/**
* #uploadprofilephoto #5
* If any error happens, Optional.empty() is returned.
*/
private Optional<FileEntity> save(FileEntity file) {
System.out.println("---------------------------------------------------- ");
System.out.println("                        #5 - Save   ");
System.out.println("---------------------------------------------------- ");
FileEntity savedUser = fileRepository.save(file);
System.out.println("---->#5 : savedUser: "+savedUser);//pb is during the save, this consolePrint never be return when img allready exist in db
return Optional.ofNullable(savedUser);
}

CrudRepository.class中的save(((根据我的说法,'B'来自此保存(


@NoRepositoryBean
public interface CrudRepository<T, ID> extends Repository<T, ID> {
/**
* Saves a given entity. Use the returned instance for further operations as the save operation might have changed the
* entity instance completely.
*
* @param entity must not be {@literal null}.
* @return the saved entity will never be {@literal null}.
*/
<S extends T> S save(S entity);
[...]
}

终端出现故障时:

(看2(屏幕截图1/2屏幕截图1/2

终端工作时:

屏幕截图

有人知道如何解决我的问题吗?

我认为解决方案是任一:

  • 如果fileName allready存在,只需通过newOne更改id(或者捕获其id并将其用于用户数据库中的imageId(或:-如果fileName allready存在,请将其删除并保存newOne

您觉得这个解决方案怎么样?如何用Java编写代码?

我修复了我的pb。根据规范的更新,我在数据库和目录中为每个用户只保留一个img/avatar。

因此,我通过deleteAllByUserIdAndCategory(user.id,"avatar"(更改了删除(user.imageId(。

最新更新