我用express 3在node.js中创建了一个文件上传函数。
我想抓取图像的文件扩展名。所以我可以重命名文件,然后附加文件扩展名。
app.post('/upload', function(req, res, next) {
var is = fs.createReadStream(req.files.upload.path),
fileExt = '', // I want to get the extension of the image here
os = fs.createWriteStream('public/images/users/' + req.session.adress + '.' + fileExt);
});
如何在node.js中获得图像的扩展名?
const path = require('path');
function getExt(str) {
const basename = path
.basename(str)
// Patch: for hidden files
// Removes all dots at the beginning of a line
.replace(/^(\.+)/i, '');
const firstDot = basename.indexOf('.');
const lastDot = basename.lastIndexOf('.');
const extname = path.extname(basename).replace(/(\.[a-z0-9]+).*/i, '$1');
if (firstDot === lastDot) {
return extname;
}
return basename.slice(firstDot, lastDot) + extname;
}
const files = [
'/home/charlike/bar/.hidden.tar.gz~', // ".tar.gz"
'/home/charlike/bar/file.tar.gz~', // ".tar.gz"
'/home/charlike/bar/file.tar.gz+cdf2', // ".tar.gz"
'/home/charlike/bar/file.tar.gz?quz=zaz', // ".tar.gz"
];
const fileAndExt = files.map((file) => [ file, getExt(file) ]);
console.log(JSON.stringify(fileAndExt, null, 2));
下面的函数分割字符串并返回名称和扩展名,无论扩展名中有多少个点。如果没有扩展名,则返回空字符串。以点和/或空格开头的名字也可以。
function basext(name) {
name = name.trim()
const match = name.match(/^(\.+)/)
let prefix = ''
if (match) {
prefix = match[0]
name = name.replace(prefix, '')
}
const index = name.indexOf('.')
const ext = name.substring(index + 1)
const base = name.substring(0, index) || ext
return [prefix + base, base === ext ? '' : ext]
}
const [base, ext] = basext('hello.txt')