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 で画像の拡張子を取得するにはどうすればよいですか?
ベストアンサー1
ファイル名の拡張子を取得するには、次のようにすればよいと思います。
var path = require('path')
path.extname('index.html')
// returns
'.html'
ファイル名のすべての拡張子を取得したい場合 (例: filename.css.gz
=> css.gz
)、次を試してください:
const ext = 'filename.css.gz'
.split('.')
.filter(Boolean) // removes empty extensions (e.g. `filename...txt`)
.slice(1)
.join('.')
console.log(ext) // prints 'css.gz'