Węzeł.js get rozszerzenie pliku

Im tworzy funkcję przesyłania plików w węźle.js z ekspresem 3.

Chciałbym pobrać rozszerzenie pliku obrazu. więc mogę zmienić nazwę pliku, a następnie dołączyć rozszerzenie pliku do niego.

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

Jak mogę uzyskać rozszerzenie obrazu w node.js?

Author: georgesamper, 2012-06-02

9 answers

Wierzę, że możesz wykonać następujące czynności, aby uzyskać rozszerzenie nazwy pliku.

var path = require('path')

path.extname('index.html')
// returns
'.html'
 319
Author: Snowfish,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-04-26 07:10:25

Update

Ponieważ oryginalna odpowiedź, extname () została dodana do modułu path, Zobacz odpowiedź Snowfish

Oryginalna odpowiedź:

Używam tej funkcji, aby uzyskać rozszerzenie pliku, ponieważ nie znalazłem sposobu, aby zrobić to w łatwiejszy sposób (ale myślę, że jest):

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

Musisz wymagać 'path', aby go użyć.

Inna metoda, która nie używa modułu path:

function getExtension(filename) {
    var i = filename.lastIndexOf('.');
    return (i < 0) ? '' : filename.substr(i);
}
 30
Author: dievardump,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-28 00:19:46
// you can send full url here
function getExtension(filename) {
    return filename.split('.').pop();
}

Jeśli używasz express, Dodaj następujący wiersz podczas konfigurowania middleware (bodyParser)

app.use(express.bodyParser({ keepExtensions: true}));
 16
Author: Kamrul,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-09-06 02:26:46

To rozwiązanie obsługuje 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'
 10
Author: aleclarson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-01 22:37:20

O wiele bardziej efektywne jest stosowanie metody substring() zamiast split() & pop()

Spójrz na różnice wydajności tutaj: http://jsperf.com/remove-first-character-from-string

// returns: 'html'
var path = require('path');
path.extname('index.html').substring(1);
 6
Author: magikMaker,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-28 13:00:28

Proste rozwiązanie bez potrzeby stosowania require, które rozwiązuje problem wielokrotnego wydłużania okresu:

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

Lub jeśli nie chcesz wiodącej kropki:

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

Upewnij się, że plik ma również rozszerzenie.

 6
Author: smileham,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-17 20:32:20

Myślę, że mapowanie nagłówka Content-Type w żądaniu również zadziała. Będzie to działać nawet w przypadku przesłania pliku bez rozszerzenia. (gdy nazwa pliku nie ma rozszerzenia w żądaniu)

Załóżmy, że wysyłasz swoje dane za pomocą 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--

Tutaj nazwa nagłówek Content-Type zawiera typ MIME danych. Mapowanie tego typu mime do rozszerzenia da ci rozszerzenie pliku :).

Restify BodyParser konwertuje ten nagłówek do właściwość o nazwie typ

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

Możesz użyć tego nagłówka i mapować rozszerzenie (podłańcuch itp ...) ręcznie, ale są też gotowe do tego biblioteki. Poniżej dwa były najlepsze wyniki, gdy zrobiłem wyszukiwania google

  • mime
  • MIME-typy

I ich użycie jest również proste:

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

Powyższy fragment wyświetli png na konsoli.

 3
Author: rozaydin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-20 13:49:27
var fileName = req.files.upload.name;

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

var extension = arr[length-1];
 2
Author: rajesh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-05 09:41:26

path.extname zrobi sztuczkę w większości przypadków. Jednak będzie on zawierał wszystko po ostatnim ., w tym łańcuch zapytania i fragment skrótu żądania http:

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

W takich przypadkach, będziesz chciał spróbować czegoś takiego:

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'

Zauważ, że rozszerzenia z wieloma okresami (takie jak .tar.gz), w ogóle nie będą działać z path.extname.

 1
Author: dug,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-11-19 03:52:39