I am trying to create a picture upload feature using JavaScript, but I am facing some issues. How can I allow users to upload an image, display a preview of the selected file, and handle the upload process effectively? Additionally, what steps should I take to validate the file type and size before uploading? Could you provide a detailed explanation or sample code for implementing this functionality? Any tips for integrating the upload with a server would also be appreciated.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Picture Upload</title>
</head>
<body>
<h1>Upload a Picture</h1>
<form id="uploadForm">
<input type="file" id="pictureInput" accept="image/*">
<button type="button" id="uploadButton">Upload</button>
</form>
<div id="preview">
<h2>Image Preview:</h2>
<img id="previewImage" src="" alt="Image Preview" style="max-width: 300px; display: none;">
</div>
<script>
// Select DOM elements
const pictureInput = document.getElementById('pictureInput');
const previewImage = document.getElementById('previewImage');
const uploadButton = document.getElementById('uploadButton');
// Event listener for file input
pictureInput.addEventListener('change', function(event) {
const file = event.target.files[0];
if (file) {
const reader = new FileReader();
// Show the preview once the file is loaded
reader.onload = function(e) {
previewImage.src = e.target.result;
previewImage.style.display = 'block';
};
// Read the file as a data URL
reader.readAsDataURL(file);
}
});
// Simulated upload button (can replace with actual server upload code)
uploadButton.addEventListener('click', function() {
const file = pictureInput.files[0];
if (!file) {
alert('Please select an image to upload.');
return;
}
// Display a success message (or handle server upload)
alert(`File "${file.name}" is ready to be uploaded!`);
});
</script>
</body>
</html>