In my file API setup, I successfully save a file. However, in the service and controller layers, when I attempt to retrieve all files associated with a specific user, JavaScript calls the endpoint but only displays a blank box. There are no visible errors.
So, initially, I stored the file as a byte[]. When I called the endpoint from JavaScript, the backend encoded it into base64. This encoded data is then displayed in a container where multiple files can be organized in rows. Previously, when there was an issue, it showed a broken image icon/blank box.
FileService:
public File uploadFile(Profile profile, MultipartFile file) throws IOException {
logger.info("FileService - Uploading file for profile ID: {}", profile.getId());
File uploadedFile = new File();
uploadedFile.setProfile(profile);
uploadedFile.setFileName(file.getOriginalFilename());
uploadedFile.setFileType(file.getContentType());
uploadedFile.setFileSize(file.getSize());
uploadedFile.setUploadDate(LocalDate.now());
uploadedFile.setFileContent(file.getBytes());
uploadedFile = fileRepository.save(uploadedFile);
logger.info("FileService - File uploaded successfully. File ID: {}", uploadedFile.getId());
return uploadedFile;
}
fileController:
@PostMapping("/upload/{profileId}")
public ResponseEntity<File> uploadFile(@PathVariable Long profileId, @RequestParam("file") MultipartFile file) {
logger.info("FileController - Uploading file for profile ID: {}", profileId);
Optional<Profile> optionalProfile = profileRepository.findById(profileId);
if (optionalProfile.isPresent()) {
Profile profile = optionalProfile.get();
try {
File uploadedFile = fileService.uploadFile(profile, file); // Delegate to service
logger.info("FileController - File uploaded successfully for profile ID: {}", profileId);
return ResponseEntity.status(HttpStatus.CREATED).body(uploadedFile);
} catch (IOException e) {
logger.error("FileController - Error uploading file for profile ID: {}", profileId, e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
} else {
logger.warn("FileController - Profile not found for ID: {}", profileId);
return ResponseEntity.notFound().build();
}
}
Javascript to display file and encode it to base64
function displayFile(file) {
console.log('File to display:', file);
const fileContainer = document.getElementById('fileContainer');
const fileElement = document.createElement('div');
fileElement.classList.add('file-item');
// Set background image using base64 encoded string provided by backend
fileElement.style.backgroundImage = `url('data:${file.fileType};base64,${file.fileContent}')`;
fileElement.title = file.fileName;
// Add click event to show file in modal
fileElement.addEventListener('click', () => showFileInModal(file));
// Append the file element to the file container
fileContainer.appendChild(fileElement);
}
css file
.file-container {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 20px;
max-height: calc(100vh - 200px); /* Adjust height as needed */
overflow-y: auto;
}
.file-item {
display: inline-block;
width: 200px;
height: 200px;
background-size: cover;
background-position: center;
border: 1px solid #ccc;
}
.file-thumbnail {
max-width: 100%; /* Adjust to fit your container width */
height: auto; /* Maintain aspect ratio */
}
.file-details {
flex: 2;
}
html file where the files are being displayed
<div class="content mt-4">
<div class="file-container" id="fileContainer">
<!-- Files will be dynamically added here -->
</div>
<div id="uploadMessage" class="mt-3"></div> <!-- Element for upload status message -->
<!-- Main content goes here -->
</div>
I am using google chrome, if that info is needed as well.
outcome on screen:
result of taking the byte file -> base64 encode and display