Получить расширение файла javascript

File: type property

Returns the media type (MIME) of the file represented by a File object.

Value

A string, containing the media type(MIME) indicating the type of the file, for example «image/png» for PNG images

Examples

HTML

input type="file" id="filepicker" name="fileList" multiple /> output id="output">output> 
output  display: block; white-space: pre-wrap; > 

JavaScript

const output = document.getElementById("output"); const filepicker = document.getElementById("filepicker"); filepicker.addEventListener("change", (event) =>  const files = event.target.files; output.textContent = ""; for (const file of files)  output.textContent += `$file.name>: $file.type || "unknown">\n`; > >); 

Result

Note: Based on the current implementation, browsers won’t actually read the bytestream of a file to determine its media type. It is assumed based on the file extension; a PNG image file renamed to .txt would give «text/plain» and not «image/png«. Moreover, file.type is generally reliable only for common file types like images, HTML documents, audio and video. Uncommon file extensions would return an empty string. Client configuration (for instance, the Windows Registry) may result in unexpected values even for common types. Developers are advised not to rely on this property as a sole validation scheme.

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Apr 7, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

Node.js get file extension

Im creating a file upload function in node.js with 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); >); 

16 Answers 16

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' 

If you would like to get all extensions in a file name (e.g. filename.css.gz => css.gz ), try this:

const ext = 'filename.css.gz' .split('.') .filter(Boolean) // removes empty extensions (e.g. `filename. txt`) .slice(1) .join('.') console.log(ext) // prints 'css.gz' 

Just be careful, it will only grab the characters after the last dot, so file names like app.css.gz will only return .gz and not .css.gz , which may or may not be what you want.

Generally the extension is the last one. And for when we are expecting more then one, like tar.gz for example. it’s better to check if it exist in the end or not. using regex for example. «tar.gz$» or by building up a function that do that. like checking that from the end and going back and see if it match totally. and you will have that function that check the extension. WHY? because what about files like jone.lastTest.654654556.tar.gz here the extension that’s expected is tar.gz but if you apply any function that give form 1st dot, it will not work as you can see

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

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)

you must require ‘path’ to use it.

another method which does not use the path module :

function getExtension(filename)

Yeah that works. Just thought there would be an easier way using node. This is what i did: var is = fs.createReadStream(req.files.upload.path), fileType = is.path.split(/[. ]+/).pop();

You should really just use the path module, as @Snowfish’s answer pointed out, and not write your own. More info: nodejs.org/api/path.html#path_path_extname_p

// you can send full url here function getExtension(filename)

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

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

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

enter image description here

Update August 2019 As 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.

There is a warning now for substr it is considered a legacy function and should be avoided when possible — More information on MDN

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' 
const path = require('path'); const < ext >= path.parse('/home/user/dir/file.txt'); 

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

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.

import extname in order to return the extension the file:

import < extname >from 'path'; extname(file.originalname); 

where file is the file ‘name’ of form

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)

Assume you are sending your data using 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 :).

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

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

and their usage is simple as well:

 app.post('/upload2', function (req, res)

above snippet will print png to console.

Источник

javascript — get the filename and extension from input type=file

I have a file upload input and when I click the browse button and select the file, I want the filename and extension to appear in two input text boxes (see code sample). It works correctly with the extension, but the filename also shows the path which gives me the fakepath warning. I understand why, but what’s a good way to do this and just get the filename into that box. I don’t need the path.

  
Output Filename
Extension

Sorry to highjack this, but someone deleted my answer to this thread where you said that you had just submitted an app to the App Store and got that UIWebView deprecation warning: stackoverflow.com/questions/57700996/… I’m very curious if Apple will reject it based on the UIWebView usage. Can you please let me know?

10 Answers 10

This is bit old post. just for info

 var files = event.target.files var filename = files[0].name var extension = files[0].type 

In the type you will find the extension for eg: if it is jpeg image then,

extension = application/pdf 

To obtain the exact value, perform extension.replace(/(.*)\//g, »). you will get the value.

This is very neat, but comes with a «but». The type property might return empty strings. For example, if you upload a docx file as a client, but don’t have MS Word installed on your client machine, then the browser returns an empty string on type . Fallback mechanisms are necessary. This behaves differently though in each browser. I’ve seen this empty string result on type with the latest/recent Chrome version and no MS Word installed on my dev machine.

Incase I upload the *.docx file it returns like this. application/vnd.openxmlformats-officedocument.wordprocessingml.document How can I get only extension «docx»?

Источник

Читайте также:  Break continue and pass in python
Оцените статью