我读了这个和这个问题,似乎表明文件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的时刻?还是我遗漏了什么?
正如在其他答案中所述,您可以通过检查文件的第一个字节中的文件签名来检查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>
正如Drake所说,这可以用FileReader完成。然而,我在这里介绍的是一个功能版本。请注意,使用JavaScript执行此操作的最大问题是重置输入文件。好吧,这仅限于JPG(对于其他格式,你将不得不改变mime类型和魔术数字):
<form id="form-id">
<input type="file" id="input-id" accept="image/jpeg"/>
</form>
<script type="text/javascript">
$(function(){
$("#input-id").on('change', function(event) {
var file = event.target.files[0];
if(file.size>=2*1024*1024) {
alert("JPG images of maximum 2MB");
$("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
return;
}
if(!file.type.match('image/jp.*')) {
alert("only JPG images");
$("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
return;
}
var fileReader = new FileReader();
fileReader.onload = function(e) {
var int32View = new Uint8Array(e.target.result);
//verify the magic number
// for JPG is 0xFF 0xD8 0xFF 0xE0 (see https://en.wikipedia.org/wiki/List_of_file_signatures)
if(int32View.length>4 && int32View[0]==0xFF && int32View[1]==0xD8 && int32View[2]==0xFF && int32View[3]==0xE0) {
alert("ok!");
} else {
alert("only valid JPG images");
$("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
return;
}
};
fileReader.readAsArrayBuffer(file);
});
});
</script>
考虑到这是在最新版本的Firefox和Chrome以及IExplore 10上进行的测试。
有关mime类型的完整列表,请参阅维基百科。
有关魔法数字的完整列表,请参阅维基百科。
对于Png文件,你可以做更多的检查,而不仅仅是检查一些神奇的头字节,因为Png文件有一个特定的文件格式,你可以检查。
TLDR:有一系列必须以特定顺序排列的块,并且每个块都有一个crc错误纠正码,您可以检查它是否有效。
https://en.wikipedia.org/wiki/Portable_Network_Graphics#File_format
我做了一个小库,检查块布局是正确的,它检查每个块的crc代码是有效的。准备作为npm包在这里消费:
https://www.npmjs.com/package/png-validator
正如在其他答案中所述,您可以通过检查文件的第一个字节中的文件签名来检查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>