我想构建检查文件类型的 Javascript 代码。在我创建的 Web 应用程序中,允许用户上传文档文件 viz
、doc
、xls
、ppt
、docx
、xlsx
、pptx
、txt
>、rar
、zip
、pdf
、jpg
、png
、 gif
、jpeg
、odt
,但不应允许其他文件。我无法仅检查文件名中的扩展名。用户可以更改它。
我尝试检查内容类型,但它每次都会发生变化。欢迎提出建议。
最佳答案
在“现代”浏览器(IE10+、Firefox 4+、Chrome 7+、Safari 6.0.2+ 等)中,您可以使用 File
/FileReader
API 用于读取文件内容并在客户端解析它。例如。 (示例,不是生产代码):
var fileInput = /* Your <input type="file"> element */
fileInput.addEventListener("change", function(e) {
var file = e.currentTarget.files[0];
var reader = new FileReader();
reader.onload = fileLoaded;
reader.readAsArrayBuffer(file);
});
function fileLoaded(e)
{
var arrayBuffer = e.currentTarget.result;
// 32 indicates that we just want a look at the first 32 bytes of the buffer.
// If we don't specify a length, we get the entire buffer.
var bytes = new Uint8Array(arrayBuffer, 0, 32);
// Now we can check the content, comparing to whatever file signatures we
// have, e.g.:
if (bytes[0] == 0x50 &&
bytes[1] == 0x4b &&
bytes[2] == 0x03 &&
bytes[3] == 0x04)
{
// This is most likely docx, xlsx, pptx or other zip file.
}
}
但是请注意,例如a .zip 没有以 50 4b 03 04 开头。因此,除非您花费大量时间研究不同的文件签名(或找到一些已经这样做的库),否则您'我们可能会拒绝实际上可能有效的文件。当然,它也有可能会给出误报。
不过,在这种情况下,误报并不那么重要 - 因为这仅作为一种用户友好的措施有用,用于检查用户是否上传了无论如何都会被服务器拒绝的文件。服务器应该始终验证它最终发送的内容。
当然,读取整个文件来查看前几个字节也不是那么有效。 :-) 请参阅 Ray Nicholus 对此的评论。
关于javascript - 如何检查文件的类型与其扩展名相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23578501/