我读了这个和这个问题,似乎表明文件MIME类型可以在客户端使用JavaScript检查。现在,我知道真正的验证仍然必须在服务器端完成。我想执行客户端检查,以避免不必要的服务器资源浪费。

为了测试这是否可以在客户端完成,我将一个JPEG测试文件的扩展名更改为.png,并选择该文件进行上传。在发送文件之前,我使用JavaScript控制台查询文件对象:

document.getElementsByTagName('input')[0].files[0];

这是我在Chrome 28.0上得到的:

文件{webkitRelativePath: "", lastModifiedDate: Tue Oct 16 2012 10:00:00 GMT+0000 (UTC),名称:“test.png”,类型:“image/png”,大小: 500055年…}

它显示的类型为image/png,这似乎表明检查是基于文件扩展名而不是MIME类型。我尝试了火狐22.0,它给了我同样的结果。但是根据W3C规范,应该实现MIME嗅探。

我是正确的说,没有办法检查MIME类型与JavaScript的时刻?还是我遗漏了什么?


当前回答

对于那些不希望自己实现这个功能的人来说,Sindresorhus创建了一个在浏览器中工作的实用程序,并为您想要的大多数文档提供了头到mime的映射。

https://github.com/sindresorhus/file-type

你可以结合受害者。us的建议是只读取前X字节,以避免使用这个实用程序将所有内容加载到内存中(es6中的示例):

import fileType from 'file-type'; // or wherever you load the dependency

const blob = file.slice(0, fileType.minimumBytes);

const reader = new FileReader();
reader.onloadend = function(e) {
  if (e.target.readyState !== FileReader.DONE) {
    return;
  }

  const bytes = new Uint8Array(e.target.result);
  const { ext, mime } = fileType.fromBuffer(bytes);

  // ext is the desired extension and mime is the mimetype
};
reader.readAsArrayBuffer(blob);

其他回答

正如在其他答案中所述,您可以通过检查文件的第一个字节中的文件签名来检查mime类型。

但是其他答案所做的是将整个文件加载到内存中以检查签名,这是非常浪费的,并且如果您无意中选择了一个大文件,很容易冻结您的浏览器。

/** * Load the mime type based on the signature of the first bytes of the file * @param {File} file A instance of File * @param {Function} callback Callback with the result * @author Victor www.vitim.us * @date 2017-03-23 */ function loadMime(file, callback) { //List of known mimes var mimes = [ { mime: 'image/jpeg', pattern: [0xFF, 0xD8, 0xFF], mask: [0xFF, 0xFF, 0xFF], }, { mime: 'image/png', pattern: [0x89, 0x50, 0x4E, 0x47], mask: [0xFF, 0xFF, 0xFF, 0xFF], } // you can expand this list @see https://mimesniff.spec.whatwg.org/#matching-an-image-type-pattern ]; function check(bytes, mime) { for (var i = 0, l = mime.mask.length; i < l; ++i) { if ((bytes[i] & mime.mask[i]) - mime.pattern[i] !== 0) { return false; } } return true; } var blob = file.slice(0, 4); //read the first 4 bytes of the file var reader = new FileReader(); reader.onloadend = function(e) { if (e.target.readyState === FileReader.DONE) { var bytes = new Uint8Array(e.target.result); for (var i=0, l = mimes.length; i<l; ++i) { if (check(bytes, mimes[i])) return callback("Mime: " + mimes[i].mime + " <br> Browser:" + file.type); } return callback("Mime: unknown <br> Browser:" + file.type); } }; reader.readAsArrayBuffer(blob); } //when selecting a file on the input fileInput.onchange = function() { loadMime(fileInput.files[0], function(mime) { //print the output to the screen output.innerHTML = mime; }); }; <input type="file" id="fileInput"> <div id="output"></div>

对于那些不希望自己实现这个功能的人来说,Sindresorhus创建了一个在浏览器中工作的实用程序,并为您想要的大多数文档提供了头到mime的映射。

https://github.com/sindresorhus/file-type

你可以结合受害者。us的建议是只读取前X字节,以避免使用这个实用程序将所有内容加载到内存中(es6中的示例):

import fileType from 'file-type'; // or wherever you load the dependency

const blob = file.slice(0, fileType.minimumBytes);

const reader = new FileReader();
reader.onloadend = function(e) {
  if (e.target.readyState !== FileReader.DONE) {
    return;
  }

  const bytes = new Uint8Array(e.target.result);
  const { ext, mime } = fileType.fromBuffer(bytes);

  // ext is the desired extension and mime is the mimetype
};
reader.readAsArrayBuffer(blob);

简短的回答是否定的。

正如您所注意到的,浏览器从文件扩展名派生类型。Mac预览似乎也运行了扩展。我假设这是因为它更快地读取包含在指针中的文件名,而不是查找和读取磁盘上的文件。

我复制了一个重命名为png的jpg文件。

我能够始终如一地从chrome中的两个图像中获得以下内容(应该在现代浏览器中工作)。

ÿØÿàJFIFÿþ;CREATOR: gd-jpeg v1.0(使用IJG JPEG v62),质量= 90

你可以通过String.indexOf('jpeg')检查图像类型。

这里有一个琴来探索http://jsfiddle.net/bamboo/jkZ2v/1/

例子中我忘记注释的含糊行

console.log( /^(.*)$/m.exec(window.atob( image.src.split(',')[1] )) );

拆分base64编码的img数据,保留在映像上 Base64解码映像 只匹配图像数据的第一行

提琴代码使用base64解码,这不会在IE9工作,我确实找到了一个很好的例子,使用VB脚本,在IE http://blog.nihilogic.dk/2008/08/imageinfo-reading-image-metadata-with.html工作

加载图像的代码来自Joel Vardy,他正在做一些很酷的图像画布调整客户端,然后上传,这可能是感兴趣的https://joelvardy.com/writing/javascript-image-upload

这是你必须要做的

var fileVariable =document.getElementsById('fileId').files[0];

如果你想检查图像文件类型,那么

if(fileVariable.type.match('image.*'))
{
 alert('its an image');
}

如果你只是想检查上传的文件是否是一张图像,你可以尝试将它加载到<img>标签中,检查是否有任何错误回调。

例子:

var input = document.getElementsByTagName('input')[0];
var reader = new FileReader();

reader.onload = function (e) {
    imageExists(e.target.result, function(exists){
        if (exists) {

            // Do something with the image file.. 

        } else {

            // different file format

        }
    });
};

reader.readAsDataURL(input.files[0]);


function imageExists(url, callback) {
    var img = new Image();
    img.onload = function() { callback(true); };
    img.onerror = function() { callback(false); };
    img.src = url;
}