Search code examples
htmlformsfile-uploadbrowser

Use `enctype="multipart/form-data"` always or never?


I want to write a generic html template.

I know that in the past you needed to set enctype="multipart/form-data" in the <form> tag, if you wanted to upload files.

I would like to avoid this condition in my generic template.

What should I do? I see these solutions:

  • use enctype="multipart/form-data" always.
  • use enctype="multipart/form-data" never.

Background: I am lucky, I don't need to support old browsers. I don't need to support IE9 or older versions.

It's working

We are using enctype="multipart/form-data" since several month in all forms (even if there are no files to upload).

It works. This makes our templates simpler. For me it is one simple step to the big goal "conditionlesscode".


Solution

  • When uploading a file in your form, you should specify the encoding as "multipart/form-data".

    If you want to keep your form generic, omit this attribute in the form and directly override it using formenctype attribute of input or button elements (only possible in browsers with HTML5 support). In your case, change:

    <form action="upload.php" method="post" enctype="multipart/form-data">
      Select image to upload:
      <input type="file" name="fileToUpload" id="fileToUpload">
      <input type="submit" value="Upload Image" name="submit">
    </form>
    

    to:

    <form action="upload.php" method="post">
      Select image to upload:
      <input type="file" name="fileToUpload" id="fileToUpload" formenctype="multipart/form-data">
      <input type="submit" value="Upload Image" name="submit">
    </form>
    

    Also, you can check this question where it was recommended to avoid always using enctype="multipart/form-data".