Skip to content

Commit

Permalink
Add thumbnail when file is image; refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
jimsafley committed Nov 28, 2023
1 parent 8c2a335 commit 9958bab
Showing 1 changed file with 41 additions and 11 deletions.
52 changes: 41 additions & 11 deletions application/asset/js/item-manage-media.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,23 +35,53 @@ $('#item-media').on('click', 'a.remove-new-media-field', function(e) {

// Handle file selection for upload media.
$(document).on('change', '.media-file-input', function(e) {

const thisFileInput = $(this);
// Iterate every file in the file list.
const thisUploadMedia = thisFileInput.closest('.media');
const additionalUploadMedia = [];

// Iterate every file in the FileList.
for (const [fileIndex, file] of Object.entries(this.files)) {
// Use the DataTransfer API to create a new FileList.
const list = new DataTransfer();
list.items.add(file);

let uploadMedia;
let fileInput;

// Use the DataTransfer API to create a new FileList containing one
// file, then set the FileList to this file input or additional file
// inputs if the original FileList contains more than one file.
const dataTransfer = new DataTransfer();
dataTransfer.items.add(file);
if (0 == fileIndex) {
// Add the first file to the already opened upload interface.
this.files = list.files;
// Add the first file to this file input.
uploadMedia = thisUploadMedia;
fileInput = thisFileInput;
} else {
// Add each subsequent file to a new upload interface.
const uploadMedia = createMediaFromTemplate('upload');
const fileInput = uploadMedia.find('.media-file-input');
fileInput[0].files = list.files;
thisFileInput.closest('.media').after(uploadMedia);
// Add each additional file to a new file input.
uploadMedia = createMediaFromTemplate('upload');
fileInput = uploadMedia.find('.media-file-input');
additionalUploadMedia.push(uploadMedia);
}
fileInput[0].files = dataTransfer.files;

// Add a thumbnail when the file is an image.
uploadMedia.find('.media-file-image').remove();
if ((/^image\/(png|jpe?g|gif)$/).test(file.type)) {
const imageSrc = URL.createObjectURL(file);
const img = new Image();
img.onload = function() {
const maxSize = 200;
const smallestPercent = Math.min(maxSize / this.width, maxSize / this.height);
img.width = this.width * smallestPercent;
img.height = this.height * smallestPercent;
uploadMedia.append(img);
}
img.src = imageSrc;
img.className = 'media-file-image';
}
}

// Append the additional upload interfaces in the order they were added.
thisUploadMedia.after(additionalUploadMedia);
});

});

0 comments on commit 9958bab

Please sign in to comment.