写一个nodejs判断上传文件类型的函数
下面是一个使用node.js的函数来判断上传文件类型的示例:
const fs = require('fs');
function getFileType(filePath) {
// 读取文件的前几个字节
const buffer = Buffer.alloc(256);
const fd = fs.openSync(filePath, 'r');
fs.readSync(fd, buffer, 0, buffer.length, 0);
fs.closeSync(fd);
// 根据文件的魔术字节判断文件类型
if (buffer.slice(0, 4).toString('hex') === '89504e47') {
return 'image/png';
} else if (buffer.slice(0, 2).toString('hex') === 'ffd8') {
return 'image/jpeg';
} else if (buffer.slice(0, 3).toString('hex') === '474946') {
return 'image/gif';
} else if (buffer.slice(0, 4).toString('hex') === '25504446') {
return 'application/pdf';
} else {
return 'unknown';
}
}
// 示例用法
const filePath = 'path/to/file.png';
const fileType = getFileType(filePath);
console.log(fileType);
上面的函数通过读取文件的前几个字节来判断文件类型。它使用fs模块的openSync、readSync和closeSync方法来读取文件内容,并根据文件的魔术字节判断文件类型。目前示例中判断了PNG、JPEG、GIF和PDF文件的类型,你可以根据需要添加其他文件类型的判断。如果无法确定文件类型,则返回'unknown'
AI 优化版
原文地址:https://www.cveoy.top/t/topic/hJZB 著作权归作者所有。请勿转载和采集!