You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何通过HTML限制上传至Google Drive的文件大小

How to Add File Size & Type Restrictions to Your Google Drive Upload Form

Hey there! Since you already have a working HTML form for uploading to Google Drive, adding file size and type checks is totally straightforward with basic JavaScript—even if you're new to it. Let's break this down step by step with clear, actionable code you can drop right into your existing setup.

First: The Core Idea

We’ll use JavaScript to listen for two key moments:

  1. When the user selects a file (so we can validate it immediately)
  2. When the user tries to submit the form (as a backup to block invalid uploads)

For each moment, we’ll check if the file meets your size and type rules. If not, we’ll show an error and stop the upload.

Step 1: Add File Size Restriction

Let’s say you want to cap files at 5MB (adjust this number to fit your needs). Here’s how to make it work:

First, make sure your file input has an ID so we can target it easily:

<input type="file" id="uploadFile" name="file">

Then add this JavaScript (place it right before the closing </body> tag, or in a script block in your HTML):

// Wait for the page to fully load before running code
document.addEventListener('DOMContentLoaded', function() {
  // Grab the file input and your form (replace IDs with your actual ones)
  const fileInput = document.getElementById('uploadFile');
  const form = document.getElementById('uploadForm');

  // Set max file size (5MB = 5 * 1024 * 1024 bytes)
  const maxSize = 5 * 1024 * 1024;

  // Check when user selects a file
  fileInput.addEventListener('change', function() {
    const selectedFile = this.files[0];
    if (!selectedFile) return;

    // If file is too big
    if (selectedFile.size > maxSize) {
      alert(`Whoops, that file's too big! Max allowed size is ${(maxSize / 1024 / 1024).toFixed(2)}MB.`);
      // Clear the input so the user can pick a new file
      this.value = '';
    }
  });

  // Backup check when form is submitted
  form.addEventListener('submit', function(e) {
    const selectedFile = fileInput.files[0];
    if (!selectedFile) return;

    if (selectedFile.size > maxSize) {
      alert(`File too large! Max size is ${(maxSize / 1024 / 1024).toFixed(2)}MB.`);
      // Stop the form from sending the invalid file
      e.preventDefault();
    }
  });
});

Quick Notes:

  • Replace uploadFile and uploadForm with your actual element IDs.
  • Adjust maxSize using the formula X * 1024 * 1024 to calculate bytes from MB (e.g., 10MB = 1010241024 = 10485760 bytes).
  • The change event catches issues early, while the submit event prevents sneaky workarounds.

Step 2: Add File Type Restriction

If you want to limit uploads to specific types (like images or PDFs), we can check either the file’s MIME type or its extension (extensions are more reliable for edge cases).

Add this inside both the change and submit event handlers (right after the size check):

// Define allowed extensions (add/remove as needed)
const allowedExtensions = ['.jpg', '.jpeg', '.png', '.pdf'];

// Get the file extension (lowercase to avoid case sensitivity issues)
const fileExtension = '.' + selectedFile.name.split('.').pop().toLowerCase();

if (!allowedExtensions.includes(fileExtension)) {
  alert('Invalid file type! Only JPG, PNG, and PDF files are allowed.');
  this.value = ''; // Clear input for change event
  e.preventDefault(); // Block submission for form event
}

Option B: Check MIME Type

If you prefer using MIME types, use this instead:

// Define allowed MIME types
const allowedTypes = ['image/jpeg', 'image/png', 'application/pdf'];

if (!allowedTypes.includes(selectedFile.type)) {
  alert('Invalid file type! Only JPG, PNG, and PDF files are allowed.');
  this.value = '';
  e.preventDefault();
}

Step 3: Combine Everything Into Your Existing Code

Here’s a full example of how your form and script might look together:

<form id="uploadForm" action="YOUR_GOOGLE_DRIVE_UPLOAD_URL" method="post" enctype="multipart/form-data">
  <input type="file" id="uploadFile" name="file" required>
  <button type="submit">Upload to Drive</button>
</form>

<script>
document.addEventListener('DOMContentLoaded', function() {
  const fileInput = document.getElementById('uploadFile');
  const form = document.getElementById('uploadForm');
  
  // Max file size: 5MB
  const maxSize = 5 * 1024 * 1024;
  // Allowed file extensions
  const allowedExtensions = ['.jpg', '.jpeg', '.png', '.pdf'];

  // Validate on file selection
  fileInput.addEventListener('change', function() {
    const selectedFile = this.files[0];
    if (!selectedFile) return;

    // Size check
    if (selectedFile.size > maxSize) {
      alert(`File too large! Max size is ${(maxSize/1024/1024).toFixed(2)}MB.`);
      this.value = '';
      return;
    }

    // Extension check
    const fileExtension = '.' + selectedFile.name.split('.').pop().toLowerCase();
    if (!allowedExtensions.includes(fileExtension)) {
      alert('Invalid file type! Only JPG, PNG, PDF are allowed.');
      this.value = '';
    }
  });

  // Validate on form submit
  form.addEventListener('submit', function(e) {
    const selectedFile = fileInput.files[0];
    if (!selectedFile) return;

    if (selectedFile.size > maxSize) {
      alert(`File too large! Max size is ${(maxSize/1024/1024).toFixed(2)}MB.`);
      e.preventDefault();
      return;
    }

    const fileExtension = '.' + selectedFile.name.split('.').pop().toLowerCase();
    if (!allowedExtensions.includes(fileExtension)) {
      alert('Invalid file type! Only JPG, PNG, PDF are allowed.');
      e.preventDefault();
    }
  });
});
</script>

Why Your Previous Attempt Might Have Failed

  • You forgot to wrap code in DOMContentLoaded: If your script ran before the HTML elements loaded, it couldn’t find your input/form.
  • You didn’t prevent form submission: Even if you showed an alert, the form still sent the invalid file.
  • Size calculation errors: Maybe you used KB instead of bytes (remember, 1MB = 1024KB = 1024*1024 bytes).

Final Tips

  • Test with different file sizes and types to confirm checks work.
  • Replace alert() with a nicer on-page error message (like a hidden <div> you show/hide) for better user experience.
  • If using multiple file uploads (multiple attribute on the input), loop through fileInput.files instead of just using files[0].

内容的提问来源于stack exchange,提问作者Primo Raj

火山引擎 最新活动