base64 url changes after refreshing the page

So im currently saving a “file” in mySQL as base64, now when a “user” logins in they can upload a file and its then displayed in a container. The “file” shows up after the upload but once you reload the page, the base64 url is completely changed and its now a blank image.

originally I was storing the “file” as a byte[] then changing it to base64 and displaying the image, at this point when you uploaded a “file” it was completely blank. So I changed how it was stored to storing it as base64, after that change the image was there after upload but then after refreshing the page, or logging out then loging back in, it was a blank image again. I”M displaying the files in a grid container so the more “files” they upload, it looks organized. So im a little lost, I changed up my javascript, css, and HTML. I have JWT so the token is good for an hour before expiring, but I dont think its the JWT at all, maybe im over looking something little. I’m sure ill figure it out eventually, just tired of going around in cycles.

uploadfile(controller)
@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();
        }
    }
uploadfile(service)
public File uploadFile(Profile profile, MultipartFile file) throws IOException {
        logger.info("FileService - Uploading file for profile ID: {}", profile.getId());

        // Convert file content to Base64 string
        String base64Content = Base64.getEncoder().encodeToString(file.getBytes());

        // Create a new File object
        File uploadedFile = new File(profile, file.getOriginalFilename(), file.getContentType(),
                file.getSize(), LocalDate.now(), base64Content);

        // Save the file to the repository
        uploadedFile = fileRepository.save(uploadedFile);

        logger.info("FileService - File uploaded successfully. File ID: {}", uploadedFile.getId());

        return uploadedFile;
    }
getting the files
@GetMapping("/{id}/files")
    public ResponseEntity<Object> getFilesByProfile(@PathVariable Long id) {
        List<File> files = profileService.getFilesByProfile(id);

        if (!files.isEmpty()) {
            return ResponseEntity.ok(files);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

getting files(service)
 public List<File> getFilesByProfile(Long profileId) {
        logger.info("ProfileService - Fetching files for profile with ID: {}", profileId);

        Optional<Profile> profile = profileRepository.findById(profileId);
        if (profile.isPresent()) {
            return fileRepository.findByProfile(profile.get());
        } else {
            // Handle case where profile with given ID is not found
            return Collections.emptyList();
        }
    }
displayfiles function
function displayFile(file) {
    console.log('File to display:', file);

    const fileContainer = document.getElementById('fileContainer');
    if (!fileContainer) {
        console.error('fileContainer element not found');
        return;
    }

    const fileElement = document.createElement('div');
    fileElement.classList.add('file-item');

    // Set background image using base64 encoded string provided by backend
    const base64Data = `data:${file.fileType};base64,${file.fileContent}`;
    console.log('Base64 data:', base64Data); // Log the base64 data
    fileElement.style.backgroundImage = `url('${base64Data}')`;
    fileElement.title = file.fileName;
    fileElement.style.backgroundSize = 'cover'; // Ensure the background image covers the entire element
    fileElement.style.backgroundPosition = 'center'; // Center the background image

    // Checkbox for selecting file
    const checkbox = document.createElement('input');
    checkbox.type = 'checkbox';
    checkbox.classList.add('file-checkbox');
    checkbox.value = file.id; // Ensure this matches the file's unique identifier
    checkbox.setAttribute('data-file-id', file.id); // Ensure this matches the file's unique identifier
    checkbox.addEventListener('click', function(event) {
        event.stopPropagation(); // Prevent triggering other click events
    });

    fileElement.appendChild(checkbox);

    // Add click event to show file in modal
    fileElement.addEventListener('click', () => showFileInModal(file));

    // Append the file element to the file container
    fileContainer.appendChild(fileElement);

    console.log('File element created and appended:', fileElement);
}
css for container holding the image
.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 {
    position: relative; /* Ensure the container is relative for absolute positioning */
    width: 200px;
    height: 200px;
    border: 1px solid #ccc;
    overflow: hidden; /* Ensure image doesn't overflow */
}

.file-item img {
    width: 100%; /* Ensure image fills the container */
    height: 100%; /* Ensure image fills the container */
    object-fit: cover; /* Maintain aspect ratio */
    display: block; /* Remove any extra space */
}
little html for where the container is held at
 <div class="content mt-4">
       <div class="file-container" id="fileContainer">
          <!-- Files will be dynamically added here -->
       </div>
  </div>

after uploading a “file”
enter image description here

after refresh
enter image description here

anyone who looks at this post, I appreciate any and all help. Hopefully I’ll be able to figure it out after a few more hours of googling 🙂