HTML input file element

Definition en français

Les éléments <input> dont l’attribut type vaut file permettent à un utilisateur de sélectionner un ou plusieurs fichiers depuis leur appareil et de les uploader vers un serveur via un formulaire ou grâce à du code JavaScript via l’API File .

Attributs supplémentaires

En complément des attributs partagés par l’ensemble des éléments <input>, les champs de type file peuvent également utiliser les attributs suivants :

accept

Une chaîne de caractères qui définit les types de fichier qui devraient être acceptés.

Cette chaîne est une liste d’identifiants de type de fichier (cf. ci-après) séparés par des virgules.

Un fichier pouvant avoir un format selon différentes extensions et types MIME , il est souvent utile de cibler plusieurs identifiants pour la bonne sélection du fichier.

Les fichiers Microsoft Word, par exemple, peuvent être identifiés de différentes façons et, dans un site avec un champ qui accepte les fichiers Word, on pourra écrire :

<input type="file" id="docpicker"
  accept=".doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document">

files

Un objet FileList qui liste chaque fichier sélectionné. Cette liste n’a qu’un seul élément, sauf si multiple est indiqué.

multiple

Lorsque cet attribut booléen est indiqué, le champ peut être utilisé afin de sélectionner plus d’un fichier.

Unique file type specifiers

A unique file type specifier is a string that describes a type of file that may be selected by the user in an <input> element of type file.

Each unique file type specifier may take one of the following forms:

  • A valid case-insensitive filename extension, starting with a period (“.”) character. For example: .jpg, .pdf, or .doc.

  • A valid MIME type string, with no extensions .

  • The string audio/* meaning “any audio file”.

  • The string video/* meaning “any video file”.

  • The string image/* meaning “any image file”.

The accept attribute takes as its value a string containing one or more of these unique file type specifiers, separated by commas.

For example, a file picker that needs content that can be presented as an image, including both standard image formats and PDF files , might look like this:

<input type="file" accept="image/*,.pdf">

Limiting accepted file types

Often you won’t want the user to be able to pick any arbitrary type of file; instead, you often want them to select files of a specific type or types.

For example, if your file input lets users upload a profile picture, you probably want them to select web-compatible image formats, such as JPEG or PNG.

Acceptable file types can be specified with the accept attribute, which takes a comma-separated list of allowed file extensions or MIME types.

Some examples:

  • accept=”image/png” or accept=”.png” Accepts PNG files.

  • accept=”image/png, image/jpeg” or accept=”.png, .jpg, .jpeg” Accept PNG or JPEG files.

  • accept=”image/ ” — Accept any file with an image/ MIME type. (Many mobile devices also let the user take a picture with the camera when this is used.)

  • accept=”.doc,.docx,.xml,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document” accept anything that smells like an MS Word document.

Let’s look at a more complete example:

Exemples

Exemple https://github.com/suzuki11109/vanilla-dnd

<html>
  <head>
    <title>Vanilla drag and drop</title>
    <link rel="stylesheet" type="text/css" href="index.css" />
  </head>
  <body>
    <div id="drop-area">
      <form class="my-form" action="">
        <p>Drop file here to upload</p>
        <input type="file" id="fileElem" multiple accept="image/*,.pdf,.py,application/msword" onchange="handleFiles(this.files)" />
        <label class="button" for="fileElem">Browse files</label>
      </form>
      <div id="gallery"></div>
    </div>
    <script src="index.js"></script>
  </body>
</html>

Javascript codes

// https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types
const fileTypes = [
  "image/apng",
  "image/bmp",
  "image/gif",
  "image/jpeg",
  "image/pjpeg",
  "image/png",
  "image/svg+xml",
  "image/tiff",
  "image/webp",
  "image/x-icon"
];

function validFileType(file) {
  return fileTypes.includes(file.type);
}

function returnFileSize(number) {
  if(number < 1024) {
    return number + 'bytes';
  } else if(number >= 1024 && number < 1048576) {
    return (number/1024).toFixed(1) + 'KB';
  } else if(number >= 1048576) {
    return (number/1048576).toFixed(1) + 'MB';
  }
}