Javascript Node.js 获取文件扩展名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10865347/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:19:17  来源:igfitidea点击:

Node.js get file extension

javascriptnode.jsfile-type

提问by georgesamper

Im creating a file upload function in node.js with express 3.

我在 node.js 中使用 express 3 创建了一个文件上传功能。

I would like to grab the file extension of the image. so i can rename the file and then append the file extension to it.

我想获取图像的文件扩展名。所以我可以重命名文件,然后将文件扩展名附加到它。

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);
});

How can i get the extension of the image in node.js?

如何在 node.js 中获取图像的扩展名?

回答by Snowfish

I believe you can do the following to get the extension of a file name.

我相信您可以执行以下操作来获取文件名的扩展名。

var path = require('path')

path.extname('index.html')
// returns
'.html'

回答by dievardump

Update

更新

Since the original answer, extname()has been added to the pathmodule, see Snowfish answer

自原始答案以来,extname()已添加到path模块中,请参阅雪鱼答案

Original answer:

原答案:

I'm using this function to get a file extension, because I didn't find a way to do it in an easier way (but I think there is) :

我正在使用此函数来获取文件扩展名,因为我没有找到一种更简单的方法(但我认为有):

function getExtension(filename) {
    var ext = path.extname(filename||'').split('.');
    return ext[ext.length - 1];
}

you must require 'path' to use it.

您必须要求“路径”才能使用它。

another method which does not use the path module :

另一种不使用路径模块的方法:

function getExtension(filename) {
    var i = filename.lastIndexOf('.');
    return (i < 0) ? '' : filename.substr(i);
}

回答by Kamrul

// you can send full url here
function getExtension(filename) {
    return filename.split('.').pop();
}

If you are using express please add the following line when configuring middleware (bodyParser)

如果你使用express请在配置中间件(bodyParser)时添加以下行

app.use(express.bodyParser({ keepExtensions: true}));

回答by magikMaker

It's a lot more efficient to use the substr()method instead of split()& pop()

使用substr()方法而不是split()&效率更高pop()

Have a look at the performance differences here: http://jsperf.com/remove-first-character-from-string

看看这里的性能差异:http: //jsperf.com/remove-first-character-from-string

// returns: 'html'
var path = require('path');
path.extname('index.html').substr(1);

enter image description here

在此处输入图片说明

Update August 2019As pointed out by @xentek in the comments; substr()is now considered a legacy function (MDN documentation). You can use substring()instead. The difference between substr()and substring()is that the second argument of substr()is the maximum length to return while the second argument of substring()is the index to stop at (without including that character). Also, substr()accepts negative start positions to be used as an offset from the end of the string while substring()does not.

2019 年 8 月更新正如@xentek 在评论中指出的那样;substr()现在被认为是一个遗留功能(MDN 文档)。你可以substring()改用。substr()和之间的区别在于substring()第二个参数substr()是返回的最大长度,而第二个参数substring()是停止的索引(不包括该字符)。此外,substr()接受负的起始位置以用作距字符串末尾的偏移量,但substring()不接受。

回答by aleclarson

This solution supports querystrings!

此解决方案支持查询字符串!

var Url = require('url');
var Path = require('path');

var url = 'http://i.imgur.com/Mvv4bx8.jpg?querystring=true';
var result = Path.extname(Url.parse(url).pathname); // '.jpg'

回答by smileham

A simple solution without need for require which solves the multiple period extension problem:

一个不需要 require 的简单解决方案,它解决了多周期扩展问题:

var filename = 'file.with.long.extension';
var ext = filename.substring(filename.indexOf('.')); 
//ext = '.with.long.extension'

Or if you don't want the leading dot:

或者,如果您不想要前导点:

var filename = 'file.with.long.extension';
var ext = filename.substring(filename.indexOf('.')+1); 
//ext = 'with.long.extension'

Make sure to test that the file has an extension too.

确保测试文件也有扩展名。

回答by rozaydin

I do think mapping the Content-Type header in the request will also work. This will work even for cases when you upload a file with no extension. (when filename does not have an extension in the request)

我确实认为在请求中映射 Content-Type 标头也可以。这甚至适用于您上传没有扩展名的文件的情况。(当文件名在请求中没有扩展名时)

Assume you are sending your data using HTTP POST:

假设您使用 HTTP POST 发送数据:

POST /upload2 HTTP/1.1
Host: localhost:7098
Connection: keep-alive
Content-Length: 1047799
Accept: */*
Origin: http://localhost:63342
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML,    like Gecko) Chrome/51.0.2704.106 Safari/537.36
Content-Type: multipart/form-data; boundary=----   WebKitFormBoundaryPDULZN8DYK3VppPp
Referer: http://localhost:63342/Admin/index.html? _ijt=3a6a054pasorvrljf8t8ea0j4h
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8,az;q=0.6,tr;q=0.4
Request Payload
------WebKitFormBoundaryPDULZN8DYK3VppPp
Content-Disposition: form-data; name="image"; filename="blob"
Content-Type: image/png


------WebKitFormBoundaryPDULZN8DYK3VppPp--

Here name Content-Type header contains the mime type of the data. Mapping this mime type to an extension will get you the file extension :).

这里 name Content-Type 头包含数据的 MIME 类型。将此 MIME 类型映射到扩展名将为您提供文件扩展名 :)。

Restify BodyParser converts this header in to a property with name type

Restify BodyParser 将此标头转换为具有名称类型的属性

File {
  domain: 
   Domain {
     domain: null,
     _events: { .... },
     _eventsCount: 1,
     _maxListeners: undefined,
     members: [ ... ] },
  _events: {},
  _eventsCount: 0,
  _maxListeners: undefined,
  size: 1047621,
  path: '/tmp/upload_2a4ac9ef22f7156180d369162ef08cb8',
  name: 'blob',
  **type: 'image/png'**,
  hash: null,
  lastModifiedDate: Wed Jul 20 2016 16:12:21 GMT+0300 (EEST),
  _writeStream: 
  WriteStream {
   ... },
     writable: true,
     domain: 
     Domain {
        ...
     },
      _events: {},
      _eventsCount: 0,
     _maxListeners: undefined,
     path: '/tmp/upload_2a4ac9ef22f7156180d369162ef08cb8',
     fd: null,
     flags: 'w',
     mode: 438,
     start: undefined,
     pos: undefined,
     bytesWritten: 1047621,
     closed: true } 
}

You can use this header and do the extension mapping (substring etc ...) manually, but there are also ready made libraries for this. Below two were the top results when i did a google search

您可以使用此标头并手动执行扩展映射(子字符串等...),但也有现成的库可用于此目的。以下两个是我进行谷歌搜索时的最佳结果

  • mime
  • mime-types
  • 哑剧
  • 哑剧类型

and their usage is simple as well:

它们的用法也很简单:

 app.post('/upload2', function (req, res) {
  console.log(mime.extension(req.files.image.type));
 }

above snippet will print pngto console.

上面的代码片段将png打印到控制台。

回答by rajesh

var fileName = req.files.upload.name;

var arr = fileName.split('.');

var extension = arr[length-1];

回答by dug

path.extnamewill do the trick in most cases. However, it will include everything after the last ., including the query string and hash fragment of an http request:

path.extname在大多数情况下都可以解决问题。但是,它将包含 last 之后的所有内容.,包括 http 请求的查询字符串和哈希片段:

var path = require('path')
var extname = path.extname('index.html?username=asdf')
// extname contains '.html?username=asdf'

In such instances, you'll want to try something like this:

在这种情况下,你会想要尝试这样的事情:

var regex = /[#\?]/g; // regex of illegal extension characters
var extname = path.extname('index.html?username=asdf');
var endOfExt = extname.search(regex);
if (endOfExt > -1) {
    extname = extname.substring(0, endOfExt);
}
// extname contains '.html'

Note that extensions with multiple periods (such as .tar.gz), will not work at all with path.extname.

请注意,带有多个句点的扩展名(例如.tar.gz),对于path.extname.

回答by Vidar

The following function splits the string and returns the name and extension no matter how many dots there are in the extension. It returns an empty string for the extension if there is none. Names that start with dots and/or white space work also.

以下函数拆分字符串并返回名称和扩展名,无论扩展名中有多少个点。如果没有扩展名,它将返回一个空字符串。以点和/或空格开头的名称也适用。

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')