Home >Web Front-end >JS Tutorial >How Can I Verify a File's MIME Type in JavaScript Before Uploading?

How Can I Verify a File's MIME Type in JavaScript Before Uploading?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-03 11:17:14506browse

How Can I Verify a File's MIME Type in JavaScript Before Uploading?

How to Check File MIME Type with JavaScript Before Upload?

JavaScript enables you to ascertain the MIME type of a file using FileReader before uploading it to a server. Although server-side checking is preferred, client-side checking is still an option. Let's explore how:

Step 1: Retrieve File Information

Obtain file details from an element as shown below:

// Retrieve file information
var files = document.getElementById("your-files").files;

Step 2: Inspect Files for MIME Type

Quick Method:

Use Blob to extract the MIME type:

console.log(files[i].type);  // Outputs "image/jpeg" or similar

Proper Header-Inspecting Method:

Analyze the file header for "magic numbers" specific to different file types:

var blob = files[i];  // File object
var fileReader = new FileReader();
fileReader.onloadend = function(e) {
  var arr = (new Uint8Array(e.target.result)).subarray(0, 4);
  var header = "";
  for(var i = 0; i < arr.length; i++) {
     header += arr[i].toString(16);
  }
  console.log(header);

  // Check the file signature against known types

};
fileReader.readAsArrayBuffer(blob);

Real MIME Type Determination:

switch (header) {
    case "89504e47":
        type = "image/png";
        break;
    case "47494638":
        type = "image/gif";
        break;
    case "ffd8ffe0":
    case "ffd8ffe1":
    case "ffd8ffe2":
    case "ffd8ffe3":
    case "ffd8ffe8":
        type = "image/jpeg";
        break;
    default:
        type = "unknown";
        break;
}

By utilizing these methods, you can determine the MIME type of files on the client side before uploading them to the server, reducing unnecessary server resource usage.

The above is the detailed content of How Can I Verify a File's MIME Type 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