CodeBlanks Logo Icon CodeBlanks

File upload

HTML course · Advanced · Lesson 20/56

Use <input type="file">, multiple and accept.

The file upload input

To upload a file you use <input type="file">. The browser shows a 'Choose file' button; the user picks a file and on submit it travels to the server.

Example: <input type="file" name="avatar">. The form tag must carry method="post" and enctype="multipart/form-data"; without them the file is not sent.

You have seen these attributes before; now we look at the file input's own multiple and accept attributes.

Multiple files with multiple

By default a file input accepts only one file. To allow several, add the multiple attribute:

<input type="file" name="photos" multiple>

Now the user can hold Ctrl (or Cmd) and pick more than one file from a folder. On the server side photos arrives as a list of files.

multiple is a boolean attribute; it has no value, its presence is enough.

Restricting types with accept

The accept attribute limits which file types can be picked. In the file dialog the user sees only matching files.

Examples:

  • accept="image/png, image/jpeg": only PNG and JPEG
  • accept="image/*": any image type
  • accept=".pdf": only PDF

accept is only a hint; the server must still verify the incoming file.

Exercise Write an avatar upload form

Add a <form> inside body. Put a <label for="avatar"> and an <input type="file" id="avatar" name="avatar"> in it. Add accept="image/png, image/jpeg" to the input (PNG and JPEG only). Also add the multiple attribute (multi-file).

Show example solution
<body>
  <form>
    <label for="avatar">Profile picture</label>
    <input type="file" id="avatar" name="avatar" accept="image/png, image/jpeg" multiple>
  </form>
</body>

Test yourself

  1. Which input type is used for a file upload field?

    • text
    • file
    • hidden
    • submit
    Show answer

    file — Correct. type="file" makes a file upload field.

  2. Complete the input for multiple files

    <input type="file" name="photos" ____>
    Show answer
    <input type="file" name="photos" multiple>
  3. Match each accept value to its file type

    image/png
    PNG image
    image/*
    All images
    .pdf
    PDF document
    image/jpeg
    JPEG image

All lessons in Advanced