Upload one file

Check the type and size in the browser, but always check again on the server.

AJAX · Upload one fileIntermediate
const input = document.getElementById('photo');

input.addEventListener('change', async function () {
  const file = input.files[0];
  if (!file) return;
  if (!/^image\/(png|jpeg|webp)$/.test(file.type)) return alert('Please choose a PNG, JPG or WebP image.');
  if (file.size > 2 * 1024 * 1024) return alert('Maximum size is 2 MB.');

  const fd = new FormData();
  fd.append('photo', file);
  const res = await fetch('/api/upload', { method: 'POST', body: fd });
  document.getElementById('msg').textContent = res.ok ? 'Uploaded' : 'Failed';
});
uploadfileFormDatainput