amalsp's picture
Add automatic download for single images
68697a0 verified
document.getElementById('imageForm').addEventListener('submit', function(e) {
e.preventDefault();
// Clear previous results
const resultsDiv = document.getElementById('results');
resultsDiv.innerHTML = '';
// Get form values
const baseUrl = document.getElementById('baseUrl').value.trim();
const imageCount = parseInt(document.getElementById('imageCount').value);
// Validate inputs
if (!baseUrl) {
resultsDiv.innerHTML = '<p class="error">Please enter a valid base URL.</p>';
return;
}
if (imageCount < 1 || imageCount > 100) {
resultsDiv.innerHTML = '<p class="error">Please enter a number between 1 and 100.</p>';
return;
}
// Special case: if imageCount is 1, download immediately
if (imageCount === 1) {
// Create a temporary anchor element
const a = document.createElement('a');
a.href = baseUrl;
a.download = ''; // This triggers download behavior
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
// Show success message
const successMsg = document.createElement('p');
successMsg.textContent = 'Image download initiated!';
successMsg.style.color = '#28a745';
successMsg.style.fontWeight = 'bold';
successMsg.style.marginTop = '15px';
resultsDiv.appendChild(successMsg);
return;
}
// Generate image links for multiple images
const title = document.createElement('h2');
title.textContent = 'Generated Image Links:';
title.style.marginTop = '20px';
title.style.color = '#333';
resultsDiv.appendChild(title);
const description = document.createElement('p');
description.textContent = 'Click any link below to view or download the image:';
description.style.color = '#666';
description.style.marginBottom = '15px';
resultsDiv.appendChild(description);
// Create links for each image
for (let i = 1; i <= imageCount; i++) {
// Check if base URL ends with a number or extension
let imageUrl;
if (baseUrl.match(/\.(jpg|jpeg|png|gif|webp|svg)$/i)) {
// If URL has extension, insert number before extension
imageUrl = baseUrl.replace(/(\.[^.]+)$/, `${i}$1`);
} else if (baseUrl.match(/\d+$/)) {
// If URL ends with a number, replace it
imageUrl = baseUrl.replace(/\d+$/, i.toString());
} else {
// Otherwise, append number
imageUrl = `${baseUrl}${i}`;
}
const link = document.createElement('a');
link.href = imageUrl;
link.className = 'image-link';
link.textContent = `Image ${i}: ${imageUrl}`;
link.target = '_blank';
link.rel = 'noopener noreferrer';
resultsDiv.appendChild(link);
}
// Add success message
const successMsg = document.createElement('p');
successMsg.textContent = `Successfully generated ${imageCount} image links!`;
successMsg.style.color = '#28a745';
successMsg.style.fontWeight = 'bold';
successMsg.style.marginTop = '15px';
resultsDiv.appendChild(successMsg);
});