Need help in validating image upload validation

Need help in validating image upload validation

Samarpanbh
Visitor
1 0 0
I developed a file uploader for my Shopify site, but it fails when handling larger files. How can I validate the file size to ensure it meets certain limits?

Here's the code :

<style>
.file-upload-container {
display: flex;
align-items: center;
}
.file-name {
margin-left: 10px;
font-style: italic;
}
.loading-message {
color: blue;
font-weight: bold;
margin-top: 10px;
}
.file-list {
margin-top: 10px;
display: flex;
flex-wrap: wrap;
}
.file-item {
display: flex;
flex-direction: column;
align-items: center;
margin-right: 10px;
margin-top: 10px;
}
.file-item img {
max-width: 100px;
max-height: 100px;
border: 1px solid #ccc;
margin-bottom: 5px;
}
.remove-button {
background-color: red;
color: white;
border: none;
padding: 2px 5px;
cursor: pointer;
}
.remove-button:hover {
background-color: darkred;
}
</style>

<div class="product-form__input">
<label class="form__label">Your photos</label>
<div class="file-upload-container">
<input id="file-your-photos" form="{{ 'product-form-' | append: section.id }}"
name="properties[Your photos 1]" multiple style="display: none;" type="file" />
<button id="button-your-photos" class="button">Upload Files</button>
<p id="fileName-your-photos" class="file-name">No file chosen</p>
</div>
<p id="errorMessage" class="error-message" style="display: none; margin-top: 0; color: red;">Please upload your file(s).</p>
<p id="loadingMessage" class="loading-message" style="display: none;">Please wait, your files are being uploaded...</p>
<div id="fileList" class="file-list"></div>
</div>

<script>
let allFiles = []; // Array to store all uploaded files

document.getElementById('file-your-photos').addEventListener('change', function(event) {
const fileInput = document.getElementById('file-your-photos');
const originalForm = fileInput.getAttribute('form');

// Add new files to the allFiles array
const newFiles = Array.from(event.target.files);
allFiles = allFiles.concat(newFiles);

// Clear previous hidden inputs
fileInput.parentNode.querySelectorAll('.dynamic-hidden-input-your-photos').forEach(input => input.remove());

// Create hidden inputs for each file in the allFiles array
for (let i = 0; i < allFiles.length; i++) {
const file = allFiles[i];
const hiddenInput = document.createElement('input');
hiddenInput.type = 'file';
let myindex = i + 1;
hiddenInput.name = 'properties[Your photos ' + myindex + ']';
hiddenInput.classList.add('dynamic-hidden-input-your-photos');
hiddenInput.classList.add('hidden-input-fileupload');
hiddenInput.style.display = 'none';
hiddenInput.setAttribute('form', originalForm);
const dataTransfer = new DataTransfer();
dataTransfer.items.add(file);
hiddenInput.files = dataTransfer.files;
fileInput.parentNode.appendChild(hiddenInput);
}

// Display the list of uploaded images
updateFileList();

// Simulate file upload process and inform the user to wait
document.getElementById('loadingMessage').style.display = 'block';
document.getElementById('button-your-photos').disabled = true; // Disable the upload button

// Simulate a delay (e.g., 2 seconds) to mock file upload time
setTimeout(function() {
document.getElementById('loadingMessage').style.display = 'none';
document.getElementById('button-your-photos').disabled = false; // Re-enable the button after the mock upload
}, 2000); // Adjust this time as per actual file upload time in real implementation
});

document.getElementById('button-your-photos').addEventListener('click', function() {
document.getElementById('file-your-photos').click();
});

// Function to update the file list and display image thumbnails with "Remove" buttons
function updateFileList() {
const fileListContainer = document.getElementById('fileList');
fileListContainer.innerHTML = ''; // Clear the list before updating

if (allFiles.length === 0) {
document.getElementById('fileName-your-photos').textContent = 'No file chosen';
return;
}

document.getElementById('fileName-your-photos').textContent = allFiles.length + ' file(s) selected';

allFiles.forEach((file, index) => {
const fileItem = document.createElement('div');
fileItem.classList.add('file-item');

// Create image thumbnail using FileReader
const reader = new FileReader();
reader.onload = function(e) {
const img = document.createElement('img');
img.src=e.target.result;
fileItem.appendChild(img);
};
reader.readAsDataURL(file);

// Add a "Remove" button for each file
const removeButton = document.createElement('button');
removeButton.classList.add('remove-button');
removeButton.textContent = 'Remove';
removeButton.setAttribute('data-index', index);
fileItem.appendChild(removeButton);

fileListContainer.appendChild(fileItem);
});

// Add click event to each "Remove" button
document.querySelectorAll('.remove-button').forEach(button => {
button.addEventListener('click', function() {
const fileIndex = this.getAttribute('data-index');
removeFile(fileIndex);
});
});
}

// Function to remove file by index
function removeFile(index) {
allFiles.splice(index, 1); // Remove the file from the array

// Update the hidden inputs
const fileInput = document.getElementById('file-your-photos');
const originalForm = fileInput.getAttribute('form');
fileInput.parentNode.querySelectorAll('.dynamic-hidden-input-your-photos').forEach(input => input.remove());

for (let i = 0; i < allFiles.length; i++) {
const file = allFiles[i];
const hiddenInput = document.createElement('input');
hiddenInput.type = 'file';
let myindex = i + 1;
hiddenInput.name = 'properties[Your photos ' + myindex + ']';
hiddenInput.classList.add('dynamic-hidden-input-your-photos');
hiddenInput.classList.add('hidden-input-fileupload');
hiddenInput.style.display = 'none';
hiddenInput.setAttribute('form', originalForm);
const dataTransfer = new DataTransfer();
dataTransfer.items.add(file);
hiddenInput.files = dataTransfer.files;
fileInput.parentNode.appendChild(hiddenInput);
}

// Update the file list UI
updateFileList();
}
</script>

Reply 1 (1)

PaulNewton
Shopify Partner
7192 636 1494

Hi @Samarpanbh  👋 use the File apis https://developer.mozilla.org/en-US/docs/Web/API/File_System_API  https://developer.mozilla.org/en-US/docs/Web/API/File 

Given an input of this: <input type="file" id="fileInput"> , use:

const input = document.getElementById('fileInput');
input.addEventListener('change', (event) => {
  const file = event.target.files[0];
  if (file) {
    console.log('File size:', file.size, 'bytes');
  }
});

 

Or literally see https://stackoverflow.com/questions/3717793/javascript-file-upload-size-validation 

 

Good Luck.

Contact [email protected] for the solutions you need


Save time & money ,Ask Questions The Smart Way


Problem Solved? ✔Accept and Like solutions to help future merchants

Answers powered by coffee Thank Paul with a Coffee for more answers or donate to eff.org