我读了这个和这个问题,似乎表明文件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);
对于Png文件,你可以做更多的检查,而不仅仅是检查一些神奇的头字节,因为Png文件有一个特定的文件格式,你可以检查。
TLDR:有一系列必须以特定顺序排列的块,并且每个块都有一个crc错误纠正码,您可以检查它是否有效。
https://en.wikipedia.org/wiki/Portable_Network_Graphics#File_format
我做了一个小库,检查块布局是正确的,它检查每个块的crc代码是有效的。准备作为npm包在这里消费:
https://www.npmjs.com/package/png-validator
我需要检查更多的文件类型。
遵循Drakes给出的优秀答案,在我发现这个网站有一个非常广泛的文件类型及其标题表后,我想出了下面的代码。都在十六进制和字符串。
我还需要一个异步函数来处理与我正在工作的项目相关的许多文件和其他问题,这些问题在这里并不重要。
下面是香草javascript代码。
// getFileMimeType
// @param {Object} the file object created by the input[type=file] DOM element.
// @return {Object} a Promise that resolves with the MIME type as argument or undefined
// if no MIME type matches were found.
const getFileMimeType = file => {
// Making the function async.
return new Promise(resolve => {
let fileReader = new FileReader();
fileReader.onloadend = event => {
const byteArray = new Uint8Array(event.target.result);
// Checking if it's JPEG. For JPEG we need to check the first 2 bytes.
// We can check further if more specific type is needed.
if(byteArray[0] == 255 && byteArray[1] == 216){
resolve('image/jpeg');
return;
}
// If it's not JPEG we can check for signature strings directly.
// This is only the case when the bytes have a readable character.
const td = new TextDecoder("utf-8");
const headerString = td.decode(byteArray);
// Array to be iterated [<string signature>, <MIME type>]
const mimeTypes = [
// Images
['PNG', 'image/png'],
// Audio
['ID3', 'audio/mpeg'],// MP3
// Video
['ftypmp4', 'video/mp4'],// MP4
['ftypisom', 'video/mp4'],// MP4
// HTML
['<!DOCTYPE html>', 'text/html'],
// PDF
['%PDF', 'application/pdf']
// Add the needed files for your case.
];
// Iterate over the required types.
for(let i = 0;i < mimeTypes.length;i++){
// If a type matches we return the MIME type
if(headerString.indexOf(mimeTypes[i][0]) > -1){
resolve(mimeTypes[i][1]);
return;
}
}
// If not is found we resolve with a blank argument
resolve();
}
// Slice enough bytes to get readable strings.
// I chose 32 arbitrarily. Note that some headers are offset by
// a number of bytes.
fileReader.readAsArrayBuffer(file.slice(0,32));
});
};
// The input[type=file] DOM element.
const fileField = document.querySelector('#file-upload');
// Event to detect when the user added files.
fileField.onchange = event => {
// We iterate over each file and log the file name and it's MIME type.
// This iteration is asynchronous.
Array.from(fileField.files, async file => {
console.log(file.name, await getFileMimeType(file));
});
};
注意,在getFileMimeType函数中,您可以使用两种方法来查找正确的MIME类型。
直接搜索字节。
在将字节转换为字符串后搜索字符串。
我对JPEG使用第一种方法,因为使其可识别的是前两个字节,而这些字节不是可读的字符串字符。
对于其余的文件类型,我可以检查可读的字符串字符签名。例如:
[视频/mp4] -> 'ftypmp4'或'ftypisom'
如果需要支持不在Gary Kessler列表中的文件,可以console.log()字节或转换后的字符串,为需要支持的模糊文件找到合适的签名。
注1:Gary Kessler的列表已经更新,现在mp4签名有所不同,您应该在实现时检查它。
注意2:Array.from被设计成使用类似.map的函数作为第二个参数。
正如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类型的完整列表,请参阅维基百科。
有关魔法数字的完整列表,请参阅维基百科。