Home >Web Front-end >JS Tutorial >How Can Browsers Reliably Check MIME Types Before File Upload?

How Can Browsers Reliably Check MIME Types Before File Upload?

DDD
DDDOriginal
2024-12-02 04:12:14299browse

How Can Browsers Reliably Check MIME Types Before File Upload?

How Browser-Side MIME Checking Works and Why It's Tricky

JavaScript can determine file MIME types before they're uploaded, but validate them on the server side for security.

Step 1: Use FileReader API

To get file information:

var files = document.getElementsByTagName('input')[0].files;
console.log(files[0].type);

Step 2: Extract MIME Type

Method 1: Using Blob (Can be fooled by file extension)

console.log(files[0].type);

Method 2: Header Inspection (More reliable)

var fileReader = new FileReader();
fileReader.onloadend = function(e) {
  var header = (new Uint8Array(e.target.result)).subarray(0, 4).toString(16);
  switch (header) {
    case "89504e47":
      type = "image/png";
      break;
    case "47494638":
      type = "image/gif";
      break;
    case "ffd8ffe0":
    case "ffd8ffe1":
    case "ffd8ffe2":
      type = "image/jpeg";
      break;
    default:
      type = "unknown";
      break;
  }
};
fileReader.readAsArrayBuffer(files[0]);

Note:

  • File extensions can be faked, so header inspection is more reliable.
  • Magic numbers may vary depending on file type.
  • Server-side validation is still essential for security.

The above is the detailed content of How Can Browsers Reliably Check MIME Types Before File Upload?. 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