Skip to content
JavaScript Beginner Updated 7h ago

PDF Upload with Type Check

PDF file upload with MIME type validation, size limit, and progress indicator.

JavaScript
Download
<input type="file" id="pdfInput" accept=".pdf,application/pdf" onchange="handlePDFUpload(event)">
<div id="pdfStatus" style="margin-top:10px"></div>
<script>
function handlePDFUpload(event) {
  const file = event.target.files[0];
  if (!file) return;
  const status = document.getElementById("pdfStatus");
  if (file.type !== "application/pdf") { status.innerHTML = '<p style="color:#ef4444">Please select a PDF file</p>'; event.target.value = ""; return; }
  if (file.size > 5 * 1024 * 1024) { status.innerHTML = '<p style="color:#ef4444">PDF must be under 5MB</p>'; event.target.value = ""; return; }
  status.innerHTML = `<p style="color:#22c55e">Selected: ${file.name} (${(file.size / 1024 / 1024).toFixed(2)} MB)</p>`;
  const formData = new FormData();
  formData.append("pdf", file);
  const xhr = new XMLHttpRequest();
  xhr.upload.addEventListener("progress", function(e) {
    if (e.lengthComputable) { const percent = Math.round((e.loaded / e.total) * 100); status.innerHTML = `<p>Uploading... ${percent}%</p>`; }
  });
  xhr.addEventListener("load", function() { status.innerHTML = '<p style="color:#22c55e">Upload complete!</p>'; });
  xhr.open("POST", "/upload-pdf");
  xhr.send(formData);
}
</script>

Technical Breakdown

PDF upload with MIME type check, size limit, and upload progress via XMLHttpRequest.

Pitfalls & Solutions

1. Only checking extension. 2. No progress feedback. 3. Not handling errors.