URL-адрес base64 изменяется после обновления страницы [закрыто]JAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 URL-адрес base64 изменяется после обновления страницы [закрыто]

Сообщение Anonymous »

Итак, в настоящее время я сохраняю «файл» в MySQL как base64, теперь, когда «пользователь» входит в систему, он может загрузить файл, а затем он отображается в контейнере. «Файл» появляется после загрузки, но как только вы перезагрузите страницу, URL-адрес base64 полностью изменится, и теперь это пустое изображение.
первоначально я сохранял «файл» как byte[], затем изменили его на base64 и отобразили изображение, на данный момент, когда вы загрузили «файл», оно было совершенно пустым. Поэтому я изменил способ его хранения, чтобы сохранить его как base64, после этого изменения изображение было там после загрузки, но затем, после обновления страницы или выхода из системы и повторного входа в систему, это снова было пустое изображение. Я показываю файлы в контейнере сетки, поэтому чем больше «файлов» они загружают, тем они выглядят организованнее. Так что я немного растерялся, я изменил свой javascript, css и HTML. У меня есть JWT, поэтому токен хорош для за час до истечения срока, но я вообще не думаю, что это JWT, может быть, я что-то не так смотрю. Я уверен, что со временем разберусь, просто устал ходить по кругу.

Код: Выделить всё

uploadfile(controller)
@PostMapping("/upload/{profileId}")
public ResponseEntity uploadFile(@PathVariable Long profileId, @RequestParam("file") MultipartFile file) {
logger.info("FileController - Uploading file for profile ID: {}", profileId);

Optional
 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 getFilesByProfile(@PathVariable Long id) {
List files = profileService.getFilesByProfile(id);

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

Код: Выделить всё

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

Optional 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





после загрузки «файла»
введите здесь описание изображения
после обновления
введите здесь описание изображения
Всем, кто просматривает этот пост, я ценю любую помощь. Надеюсь, я смогу это понять после еще нескольких часов поиска в Google :)

Подробнее здесь: https://stackoverflow.com/questions/786 ... g-the-page
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»