rjmcb
rjmcb

Reputation: 3745

How to limit the maximum files chosen when using multiple file input

When using <input type="file" multiple> it's possible for the user to choose multiple files.

How does ones sets a limit for how many files can be chosen, for instance two?

Upvotes: 111

Views: 259057

Answers (9)

P K Dhee Taal
P K Dhee Taal

Reputation: 23

Here is an example, where I am sending image through input type file. The form is submitted separately through axios on onSubmit event of form, so I am using FormData web api to send form contents as multipart/form data.

In case of handling image count, under the condition where name is equal to images, we alert the message and also set the value to empty array. Still on the UI, it will show the count of images slected so, we write the messsage clear, your images won't be sent.

Here is the properties I have given to the file input field, as a part of JS object. As I am looping through an array to populate input fields.

 {
  name: "images",
  type: "file",
  accept: "image/*",
  multiple: true,
},

And down here is the code where I have handled OnChange and Onsubmit

    const handleOnChange = (e) => {
    let { checked, name, value } = e.target;
    if (name === "status") {
      value = checked ? "active" : "inactive";
    }
    if (name === "images") {



      value = [...e.target.files];
      if (value.length > 5) {
        value = [];
        alert("Can select only upto 5 images, your images won't be sent");
      }
    }
    setForm({ ...form, [name]: value });
  };
  const handleOnSubmit = (e) => {
    e.preventDefault();
    console.log(form);

    // set data with formDataApi
    const formData = new FormData();
    for (const key in form) {
      formData.append(key, form[key]);
    }
    dispatch(postProductsAction(formData));
  };

Upvotes: 0

David
David

Reputation: 1963

This should work and protect your form from being submitted if the number of files is greater then max_file_number.

$(function() {

  var // Define maximum number of files.
      max_file_number = 3,
      // Define your form id or class or just tag.
      $form = $('form'),
      // Define your upload field class or id or tag.
      $file_upload = $('#image_upload', $form),
      // Define your submit class or id or tag.
      $button = $('.submit', $form);

  // Disable submit button on page ready.
  $button.prop('disabled', 'disabled');

  $file_upload.on('change', function () {
    var number_of_images = $(this)[0].files.length;
    if (number_of_images > max_file_number) {
      alert(`You can upload maximum ${max_file_number} files.`);
      $(this).val('');
      $button.prop('disabled', 'disabled');
    } else {
      $button.prop('disabled', false);
    }
  });
});

Upvotes: 12

Firzok Nadeem
Firzok Nadeem

Reputation: 729

In javascript you can do something like this

<input
  ref="fileInput"
  multiple
  type="file"
  style="display: none"
  @change="trySubmitFile"
>

and the function can be something like this.

trySubmitFile(e) {
  if (this.disabled) return;
  const files = e.target.files || e.dataTransfer.files;
  if (files.length > 5) {
    alert('You are only allowed to upload a maximum of 2 files at a time');
  }
  if (!files.length) return;
  for (let i = 0; i < Math.min(files.length, 2); i++) {
    this.fileCallback(files[i]);
  }
}

I am also searching for a solution where this can be limited at the time of selecting files but until now I could not find anything like that.

Upvotes: 2

Enrique
Enrique

Reputation: 381

Another possible solution with JS

function onSelect(e) {
    if (e.files.length > 5) {
        alert("Only 5 files accepted.");
        e.preventDefault();
    }
}

Upvotes: 10

Kristian Antov
Kristian Antov

Reputation: 279

On change of the input track how many files are selected:

$("#image").on("change", function() {
    if ($("#image")[0].files.length > 2) {
        alert("You can select only 2 images");
    } else {
        $("#imageUploadForm").submit();
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<strong>On change of the input track how many files are selected:</strong>
<input name="image[]" id="image" type="file"  multiple="multiple" accept="image/jpg, image/jpeg" >

Upvotes: 27

MadalinJUPANU
MadalinJUPANU

Reputation: 1

if you want php you can count the array and just make an if statement like

if((int)count($_FILES['i_dont_know_whats_coming_next'] > 2)
      echo "error message";

Upvotes: -8

You should also consider using libraries to do that: they allow limiting and much more:

They are also available at https://cdnjs.com/

Upvotes: 1

Jukka K. Korpela
Jukka K. Korpela

Reputation: 201528

Use two <input type=file> elements instead, without the multiple attribute.

Upvotes: -5

Curtis
Curtis

Reputation: 103348

You could run some jQuery client-side validation to check:

$(function(){
    $("input[type='submit']").click(function(){
        var $fileUpload = $("input[type='file']");
        if (parseInt($fileUpload.get(0).files.length)>2){
         alert("You can only upload a maximum of 2 files");
        }
    });    
});​

http://jsfiddle.net/Curt/u4NuH/

But remember to check on the server side too as client-side validation can be bypassed quite easily.

Upvotes: 83

Related Questions