- File
- Constructor
- Instance properties
- Instance methods
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- Get directory of a file name in Javascript
- 10 Answers 10
- Path module has an inbuilt function
- How to use javascript to get full file path
- Answer by Laylani Sierra
- Answer by Thalia Cantu
- Answer by Megan Cisneros
- Answer by Alejandro Hodge
- Answer by Sevyn Hogan
- Answer by Marisol Barton
- Answer by Hector Goodwin
- Example 1: how to use javascript to get full file path
- Example 2: js get file location
File
The File interface provides information about files and allows JavaScript in a web page to access their content.
File objects are generally retrieved from a FileList object returned as a result of a user selecting files using the element, or from a drag and drop operation’s DataTransfer object.
A File object is a specific kind of Blob , and can be used in any context that a Blob can. In particular, FileReader , URL.createObjectURL() , createImageBitmap() , and XMLHttpRequest.send() accept both Blob s and File s.
See Using files from web applications for more information and examples.
Constructor
Instance properties
File.prototype.lastModified Read only Returns the last modified time of the file, in millisecond since the UNIX epoch (January 1st, 1970 at Midnight). File.prototype.lastModifiedDate Deprecated Read only Non-standard Returns the last modified Date of the file referenced by the File object. File.prototype.name Read only Returns the name of the file referenced by the File object. File.prototype.webkitRelativePath Read only Returns the path the URL of the File is relative to. File implements Blob , so it also has the following properties available to it: File.prototype.size Read only Returns the size of the file in bytes. File.prototype.type Read only Returns the MIME type of the file.
Instance methods
The File interface doesn’t define any methods, but inherits methods from the Blob interface: Blob.prototype.slice([start[, end[, contentType]]]) Returns a new Blob object containing the data in the specified range of bytes of the source Blob . Blob.prototype.stream() Transforms the File into a ReadableStream that can be used to read the File contents. Blob.prototype.text() Transforms the File into a stream and reads it to completion. It returns a promise that resolves with a string (text). Blob.prototype.arrayBuffer() Transforms the File into a stream and reads it to completion. It returns a promise that resolves with an ArrayBuffer .
Specifications
Browser compatibility
See also
Found a content problem with this page?
Get directory of a file name in Javascript
@Anonymous, very good point. You would only consider using my answer if you’re on Windows and something that supports COM.
really hoping thats not in a web browser as split() or lastIndexOf would be much better than FileSystemObject
Why don’t you try path.dirname(«path/to/file») ? It will be adjusted to linux or windows path based on your environment
10 Answers 10
I don’t know if there is any built in functionality for this, but it’s pretty straight forward to get the path.
path = path.substring(0,path.lastIndexOf("\\")+1);
Your solution will only work on windows. Linux uses ‘/’ instead. It’s better to use an OS independent solution.
@Nadia the question is about Windows and path separators could be the least of his concerns with portability, we haven’t seen the code or know what he’s using it for
I agree to prefer an OS independent solution. Even if it is just for the sake of others coming to this questions. It’s a pity, this is the most upvoted answer.
If you use Node.js , path module is quite handy.
path.dirname("/home/workspace/filename.txt") // '/home/workspace/'
var dirname = filename.match(/(.*)[\/\\]/)[1]||'';
*The answers that are based on lastIndexOf(‘/’) or lastIndexOf(‘\’) are error prone, because path can be «c:\aa/bb\cc/dd».
(Matthew Flaschen did took this into account, so my answer is a regex alternative)
There’s no perfect solution, because this functionality isn’t built-in, and there’s no way to get the system file-separator. You can try:
path = path.substring(0, Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"))); alert(path);
Path module has an inbuilt function
Yes, the inbuilt module path has dirname() function, which would do the job for you.
const path = require("path"); file_path = "C:\\Program Files\\nant\\bin\\nant.exe" \\windows path file_path = "C:/Program Files/nant/bin/nant.exe" \\linux path path.dirname(file_path); \\gets you the folder path based on your OS
I see that your path is neither windows nor Linux compatible. Do not hardcode path; instead, take a reference from a path based on your OS.
I generally tackle such situations by creating relative paths using path.join(__dirname, «..», «assets», «banner.json»); .
This gives me a relative path that works regardless of the OS you are using.
function getFileDirectory(filePath) < if (filePath.indexOf("/") == -1) < // windows return filePath.substring(0, filePath.lastIndexOf('\\')); >else < // unix return filePath.substring(0, filePath.lastIndexOf('/')); >> console.assert(getFileDirectory('C:\\Program Files\\nant\\bin\\nant.exe') === 'C:\\Program Files\\nant\\bin'); console.assert(getFileDirectory('/usr/bin/nant') === '/usr/bin');
Sorry to bring this back up but was also looking for a solution without referencing the variable twice. I came up with the following:
var filepath = 'C:\\Program Files\\nant\\bin\\nant.exe'; // C:\Program Files\nant\bin\nant.exe var dirpath = filepath.split('\\').reverse().splice(1).reverse().join('\\'); // C:\Program Files\nant\bin
This is a bit of a walk through manipulating a string to array and back but it’s clean enough I think.
filepath.split("/").slice(0,-1).join("/"); // get dir of filepath
- split string into array delimited by «/»
- drop the last element of the array (which would be the file name + extension)
- join the array w/ «/» to generate the directory path
"/path/to/test.js".split("/").slice(0,-1).join("/") == "/path/to"
If isn’t a program in addressFile, return addressFile
function(addressFile) < var pos = addressFile.lastIndexOf("/"); pos = pos != -1 ? pos : addressFile.lastIndexOf("\\"); if (pos >addressFile.lastIndexOf(".")) < return addressFile; >return addressFile.substring( 0, pos+1 ); > console.assert(getFileDirectory('C:\\Program Files\\nant\\bin\\nant.exe') === 'C:\\Program Files\\nant\\bin\\'); console.assert(getFileDirectory('/usr/bin/nant') === '/usr/bin/nant/'); console.assert(getFileDirectory('/usr/thisfolderhaveadot.inhere') === '/usr/');
The core Javascript language doesn’t provide file/io functions. However if you’re working in a Windows OS you can use the FileSystemObject (ActiveX/COM).
Note: Don’t use this in the client script-side script of a web application though, it’s best in other areas such as in Windows script host, or the server side of a web app where you have more control over the platform.
This page provides a good tutorial on how to do this.
Here’s a rough example to do what you want:
var fso, targetFilePath,fileObj,folderObj; fso = new ActiveXObject("Scripting.FileSystemObject"); fileObj = fso.GetFile(targetFilePath); folderObj=fileObj.ParentFolder; alert(folderObj.Path);
How to use javascript to get full file path
How to get full path of file while selecting file using ,You can get the full path of the selected file to upload only by IE11 and MS Edge., @nauphal thanks for comment but is there any other way to get full path of selected file? – Yogesh Pingle Mar 4 ’13 at 12:08 ,Full path from file input using jQuery How to get the file path from HTML input form in Firefox 3
For security reasons browsers do not allow this, i.e. JavaScript in browser has no access to the File System, however using HTML5 File API, only Firefox provides a mozFullPath property, but if you try to get the value it returns an empty string:
$('input[type=file]').change(function () < console.log(this.files[0].mozFullPath); >);
Answer by Laylani Sierra
const onChange = (event) => < const value = event.target.value; // this will return C:\fakepath\somefile.ext console.log(value); const files = event.target.files; //this will return an ARRAY of File object console.log(files); >return ( /> ) /* Found from Stack Overflow */
Answer by Thalia Cantu
View Javascript questions
var _Profile_PIC = document.getElementById('FIP_PIC').value;
Answer by Megan Cisneros
You can use the following code to get a working local URL for the uploaded file:,For security reasons browsers do not allow this, i.e. JavaScript in browser has no access to the File System, however using HTML5 File API, only Firefox provides a mozFullPath property, but if you try to get the value it returns an empty string:,How to get full path of file while selecting file using ,71993/selected-change-input-type-file-using-javascript-jquery-ajax
How to get full path of file while selecting file using
Answer by Alejandro Hodge
How to get full path of file while selecting file using ,When a file is selected by using the input type=file object, the value of the value property depends on the value of the «Include local directory path when uploading files to a server» security setting for the security zone used to display the Web page containing the input object.,Full path from file input using jQuery How to get the file path from HTML input form in Firefox 3,but the filePath var contains only name of selected file, not the full path. I searched it on net, but it seems that for security reasons browsers (FF,chrome) just give name of file. Is there any other way to get full path of selected file?
How to get full path of file while selecting file using
Answer by Sevyn Hogan
The read-only fullPath property of the FileSystemEntry interface returns a USVString specifying the full, absolute path from the file system’s root to the file represented by the entry.,This example shows a function which is called with a file system; it then gets a FileSystemFileEntry for a file named data.json and returns its full path.,PropertiesfilesystemfullPathisDirectoryisFilename,A USVString indicating the entry’s full path.
var fullPath = FileSystemEntry.fullPath;
Answer by Marisol Barton
You can get the absolute path calculation of a relative path using path.resolve():,You can join two or more parts of a path by using path.join():,Given a path, you can extract information out of it using those methods:,Getting information out of a path
You include this module in your files using
JScopyconst path = require('path')
JScopyconst notes = '/users/joe/notes.txt' path.dirname(notes) // /users/joepath.basename(notes) // notes.txtpath.extname(notes) // .txt
You can get the file name without the extension by specifying a second argument to basename :
JScopypath.basename(notes, path.extname(notes)) //notes
You can join two or more parts of a path by using path.join() :
JScopyconst name = 'joe'path.join('/', 'users', name, 'notes.txt') //'/users/joe/notes.txt'
You can get the absolute path calculation of a relative path using path.resolve() :
JScopypath.resolve('joe.txt') //'/Users/joe/joe.txt' if run from my home folder
In this case Node.js will simply append /joe.txt to the current working directory. If you specify a second parameter folder, resolve will use the first as a base for the second:
JScopypath.resolve('tmp', 'joe.txt') //'/Users/joe/tmp/joe.txt' if run from my home folder
If the first parameter starts with a slash, that means it’s an absolute path:
JScopypath.resolve('/etc', 'joe.txt') //'/etc/joe.txt'
path.normalize() is another useful function, that will try and calculate the actual path, when it contains relative specifiers like . or .. , or double slashes:
JScopypath.normalize('/users/joe/..//test.txt') //'/users/test.txt'
Answer by Hector Goodwin
Example 1: how to use javascript to get full file path
const onChange = (event) => < const value = event.target.value; // this will return C:\fakepath\somefile.ext console.log(value); const files = event.target.files; //this will return an ARRAY of File object console.log(files); >return ( /> ) /* Found from Stack Overflow */
Example 2: js get file location
var url,foldersAndFile,folders,folderpath,protocol,host,ourLocation; url = window.location; foldersAndFile = url.pathname.split("/"); folders = foldersAndFile.slice(0,foldersAndFile.length-1); folderpath = folders.join("/"); protocol = url.protocol+"//"; host = url.host; ourLocation=protocol+host+folderpath; return ourLocation;// http://google.com/search