Node.js获取文件扩展名

时间:2012-06-02 19:37:11

标签: javascript node.js file-type

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

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

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中获取图像的扩展名?

14 个答案:

答案 0 :(得分:365)

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

var path = require('path')

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

答案 1 :(得分:30)

<强>更新

由于原始答案extname()已添加到path模块,请参阅Snowfish回答

原始回答:

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

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

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

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

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

答案 2 :(得分:17)

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

如果您使用快速,请在配置中间件(bodyParser)时添加以下行

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

答案 3 :(得分:11)

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

Meteor.call('findDB_count', function (error, result) {
    if (error) {
        alert(error.reason);
    } else {
        Session.set("count", result);
    }
});

答案 4 :(得分:8)

使用substr()方法代替split()&amp; pop()

在此处查看效果差异:http://jsperf.com/remove-first-character-from-string

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

enter image description here

答案 5 :(得分:6)

一个简单的解决方案,无需解决多周期扩展问题的需求:

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

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

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

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

答案 6 :(得分:3)

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

假设您使用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--

此处名称Content-Type标头包含数据的mime类型。 将此mime类型映射到扩展名将获得文件扩展名:)。

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

您可以使用此标头并手动执行扩展映射(substring etc ...),但也有现成的库。当我进行谷歌搜索时,下面两个是最重要的结果

  • MIME类型

它们的用法也很简单:

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

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

答案 7 :(得分:2)

var fileName = req.files.upload.name;

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

var extension = arr[length-1];

答案 8 :(得分:1)

在大多数情况下,

path.extname会做到这一点。但是,它将包括最后一个.之后的所有内容,包括http请求的查询字符串和哈希片段:

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

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

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'

请注意,包含多个句点的扩展程序(例如.tar.gz)将无法与path.extname一起使用。

答案 9 :(得分:1)

例如,您可以使用path.parse(path)

App.exit = function() {
    if (confirm("Do you want to exit?")) {

        var isRemember = localStorage.getItem('remember');
        console.log("app-rem : " + isRemember);
        if (isRemember == 'false') {
            console.log("cleared");
            localStorage.clear();
            sessionStorage.clear();
        }
        tizen.application.getCurrentApplication().exit();

    }
};

答案 10 :(得分:1)

延伸 String.prototype 的单行:

Object.defineProperty(String.prototype, "ext", {get: function(x) {return this.split('.').pop()}})
str = 'fox.fbx';
str.ext

结果:

enter image description here

答案 11 :(得分:0)

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

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

答案 12 :(得分:0)

导入扩展名以返回扩展名文件:

import { extname } from 'path';
extname(file.originalname);

其中file是表单的文件“名称”

答案 13 :(得分:0)

尝试这个

public function store(Request $request)
{
    $id = Auth::id();
    $request->user_id = $id;
    $request->validate([
        'user_id'           => 'unique:businesses',
        'business_name'     => 'required|unique:businesses|max:255|string',
        'business_type'     => 'required|string|max:255',
        'business_about'    => 'required|string',
        'business_serial'   => 'required|string|max:15',
        'business_image'    => 'required|string',
        'business_approved' => 'required|boolean',
        'bank_name'         => 'required|string|max:255',
        'account_number'    => 'required|integer',
    ]);

    $user = User::find($id);
    $business = New business;
    $business->user_id = $request->user_id;
    $business->business_name = $request->business_name;
    $business->business_type = $request->business_type;
    $business->business_about = $request->business_about;
    $business->business_serial = $request->business_serial;
    $business->business_image = $request->business_image;
    $business->business_approved = false;
    $business->account_balance = 0;
    $business->account_total = 0;
    $business->bank_name = $request->bank_name;
    $business->account_number = $request->account_number;

    $newbiz = $user->business()->save($business);

    return response(['business' => $newbiz, 'user' => $user]);
}