Пружинная загрузка и отображение изображения JavaScript в веб-браузере, сломанный значок/черный ящикJAVA

Программисты JAVA общаются здесь
Ответить Пред. темаСлед. тема
Anonymous
 Пружинная загрузка и отображение изображения JavaScript в веб-браузере, сломанный значок/черный ящик

Сообщение Anonymous »

При настройке файлового API я успешно сохраняю файл. Однако на уровнях службы и контроллера, когда я пытаюсь получить все файлы, связанные с конкретным пользователем, JavaScript вызывает конечную точку, но отображает только пустое поле. Видимых ошибок нет.
Итак, изначально я сохранил файл как byte[]. Когда я вызывал конечную точку из JavaScript, серверная часть закодировала ее в base64. Эти закодированные данные затем отображаются в контейнере, где несколько файлов могут быть организованы в строки. Раньше при возникновении проблемы отображался значок разбитого изображения или пустое поле.

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

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 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();
}
}

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

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







Я использую Google Chrome, если эта информация также необходима.
Результат на экране:
результат получения байтового файла -> кодирование и отображение base64


Подробнее здесь: https://stackoverflow.com/questions/786 ... -black-box
Реклама
Ответить Пред. темаСлед. тема

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

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

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

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

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

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