Home >Web Front-end >JS Tutorial >How Can I Verify File MIME Types in JavaScript Before Uploading?

How Can I Verify File MIME Types in JavaScript Before Uploading?

DDD
DDDOriginal
2024-12-01 17:21:11898browse

How Can I Verify File MIME Types in JavaScript Before Uploading?

How to check file MIME type with JavaScript before upload?

Possible Solutions

Despite server-side validation being essential, carrying out client-side checks can prevent unnecessary server resource consumption. While the MIME type is often determined based on file extension, that approach can be unreliable. Here's a two-step process you can follow to verify MIME types using JavaScript before uploading:

Step 1: Retrieving File Information

Obtain file details from an element as shown below:

var control = document.getElementById("your-files");
control.addEventListener("change", function(event) {
    var files = control.files,
    for (var i = 0; i < files.length; i++) {
        console.log("Filename: " + files[i].name);
        console.log("Type: " + files[i].type);
        console.log("Size: " + files[i].size + " bytes");
    }
}, false);

Step 2: Inspecting File Headers

Utilize the FileReader API to examine the file's header.

  1. Quick Method: Directly retrieve the MIME type from the file blob:

    console.log(blob.type);
  2. Reliable Method: Analyze the raw file header bytes:

    var fileReader = new FileReader();
    fileReader.onloadend = function(e) {
      // code to obtain file header goes here
    };
    fileReader.readAsArrayBuffer(blob);

Compare the header against known signatures to determine the actual MIME type. For instance, JPEG signatures could be:

case "ffd8ffe0":
case "ffd8ffe1":
case "ffd8ffe2":
    type = "image/jpeg";
    break;

Finally, accept or reject file uploads based on the expected MIME types.

Note: It's critical to realize that even if a file is renamed, its true MIME type can be established using this technique.

The above is the detailed content of How Can I Verify File MIME Types in JavaScript Before Uploading?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn