- How to get folder directory from html input type «file» or any other way?
- Method 1: Using JavaScript
- Method 2: Using a File Path Library
- Method 3: Server-side Processing
- HTML5: File Input with Folder Selection
- How to access the selected Folders via JavaScript
- Browser Support
- About the Author
- Related Topics
- Rename File to its Folder Name
- How to resize Image before Upload in Browser
- HTML5 Canvas: Beginner Tutorial Chapter 1 — Introduction and Basics
- HTML: Preassign HTML Form with Data
- Send HTML5 Canvas as Image to Server
- HTML5: Upload Images with Client Side Resize
- jQuery: Send HTML5 Canvas to Server via Ajax
- Important Note
- Participate
- How to Get Folder Directory from HTML Input Type «File» or Any Other Way
- Folder Choose in Html
- How to get full path of selected file on change of input type=‘file’ using javascript, jquery-ajax?
- HTML multi-file input to get directory (Electon app)
- How to get path segments
- See also
- [html] How to get folder directory from HTML input type «file» or any other way?
- The answer is
How to get folder directory from html input type «file» or any other way?
The HTML input type «file» allows users to select a file from their local device to upload to a web server. However, it does not provide a way to directly access the directory of the selected file. In some cases, it may be necessary to get the folder directory of the selected file, either for display purposes or to use as a part of a file path. Here are a few methods that can be used to get the folder directory from an HTML input type «file».
Method 1: Using JavaScript
To get the folder directory from an HTML input type «file» using JavaScript, you can use the following steps:
- Create an HTML input element with type «file» and an onchange event listener to trigger a function when a file is selected.
input type="file" onchange="handleFiles(this.files)">
- In the function triggered by the onchange event, access the file object and extract the file path using the webkitRelativePath property.
function handleFiles(files) const filePath = files[0].webkitRelativePath; console.log(filePath); >
- The file path extracted from the webkitRelativePath property will include the file name. To remove the file name and get only the folder directory, you can use the substring() method.
function handleFiles(files) const filePath = files[0].webkitRelativePath; const folderPath = filePath.substring(0, filePath.lastIndexOf('/')); console.log(folderPath); >
- The folder path extracted using the substring() method will include the file system root, which may vary depending on the user’s operating system. To remove the file system root and get only the relative path from the file input element, you can use the replace() method.
function handleFiles(files) const filePath = files[0].webkitRelativePath; const folderPath = filePath.substring(0, filePath.lastIndexOf('/')).replace(/^.*[\\\/]/, ''); console.log(folderPath); >
This code will log the folder directory to the console when a file is selected in the file input element. Note that this method may not work in all browsers and operating systems, as it relies on the webkitRelativePath property which is only supported in some browsers.
Method 2: Using a File Path Library
To get the folder directory from an HTML input type «file» using a file path library, you can use the following steps:
- First, you need to include the file path library in your HTML file. You can use the following code to include the library:
script src="path/to/file/path/library.js"> script>
- Next, you need to create an input element with the type «file» in your HTML file. You can use the following code to create the input element:
input type="file" id="fileInput">
- Now, you need to add an event listener to the input element to detect when a file is selected. You can use the following code to add the event listener:
document.getElementById("fileInput").addEventListener("change", function() var filePath = document.getElementById("fileInput").value; var folderPath = path.dirname(filePath); console.log(folderPath); >);
- Finally, when a file is selected, the event listener will get the file path and use the file path library to get the folder directory. The folder directory will then be logged to the console.
DOCTYPE html> html> head> title>Get Folder Directory from File Inputtitle> script src="path/to/file/path/library.js"> script> head> body> input type="file" id="fileInput"> script> document.getElementById("fileInput").addEventListener("change", function() var filePath = document.getElementById("fileInput").value; var folderPath = path.dirname(filePath); console.log(folderPath); >); script> body> html>
This code will allow you to get the folder directory from an HTML input type «file» using a file path library.
Method 3: Server-side Processing
To get the folder directory from HTML input type «file» using server-side processing, you can use the following steps:
form action="upload.php" method="post" enctype="multipart/form-data"> input type="file" name="fileToUpload" id="fileToUpload"> input type="submit" value="Upload File" name="submit"> form>
- In the server-side script (in this example, we’re using PHP), check if a file was uploaded and get the directory path using the realpath() function.
if(isset($_POST["submit"])) $target_dir = realpath($_FILES["fileToUpload"]["name"]); echo "Directory path: " . $target_dir; >
- If you want to get only the directory path without the file name, you can use the dirname() function.
if(isset($_POST["submit"])) $target_dir = realpath($_FILES["fileToUpload"]["name"]); $directory_path = dirname($target_dir); echo "Directory path: " . $directory_path; >
- To handle errors, you can check if the file was uploaded successfully and if the directory path exists.
if(isset($_POST["submit"])) $target_dir = realpath($_FILES["fileToUpload"]["name"]); if(move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_dir)) if(file_exists($target_dir)) $directory_path = dirname($target_dir); echo "Directory path: " . $directory_path; > else echo "Error: Directory path does not exist."; > > else echo "Error: File upload failed."; > >
That’s it! With these steps, you can get the folder directory from HTML input type «file» using server-side processing in PHP.
HTML5: File Input with Folder Selection
First, we have a look at the required HTML. We are using a normal input field with the type «file». In order to be able to select multiple files at once, we have added the attribute «multiple». Additionally, we have added an onchange event to read and process the folder respectively the files from the selected folder with JavaScript. We will look at the JavaScript code in the next section.
For making a directory input out of the usual file input, additionally, we have specified the attributes webkitdirectory, mozdirectory, msdirectory, odirectory and directory. Actually, specifying only the attribute «directory» should be enough at that point, but because we also want to support some older browsers, we have also added the browser specific attributes with the prefix webkit-, moz-, ms- and o-. If the browser is supporting one of those attributes, instead of the file dialog, now the directory dialog of the system is displayed.
How to access the selected Folders via JavaScript
Last, I also want to show you, how to work with the selected folder and how you are able to access the files of the folder which the user has selected.
For this, we are using the following JavaScript, which will be automatically executed when changing the folder selection, because we have assigned the function to the onchange event of the input field.
We get all files located in the selected folder in the array e.target.files.
In the code above, we are just looping through this array (the number of files is e.target.files.length) in order to show some information about the files such as name, size and type using an alert.
Browser Support
This input type is supported by the browsers Google Chrome (from version 30), Microsoft Edge (from version 14), Mozilla Firefox (from version 50) and Opera (from version 17). In contrast, the selection of folders is not supported by the Internet Explorer and many mobile browsers. This is also due to the fact that many mobile systems do not allow folders to be selected in their system at all.
About the Author
You can find Software by Stefan Trost on sttmedia.com. Do you need an individual software solution according to your needs? — sttmedia.com/contact
Show Profile
Related Topics
Rename File to its Folder Name
How to resize Image before Upload in Browser
HTML5 Canvas: Beginner Tutorial Chapter 1 — Introduction and Basics
HTML: Preassign HTML Form with Data
Send HTML5 Canvas as Image to Server
HTML5: Upload Images with Client Side Resize
jQuery: Send HTML5 Canvas to Server via Ajax
Important Note
Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.
Participate
Ask your own question or write your own article on askingbox.com. That’s how it’s done.
How to Get Folder Directory from HTML Input Type «File» or Any Other Way
Can’t be done in pure HTML/JavaScript for security reasons.
Selecting a file for upload is the best you can do, and even then you won’t get its full original path in modern browsers.
You may be able to put something together using Java or Flash (e.g. using SWFUpload as a basis), but it’s a lot of work and brings additional compatibility issues.
Another thought would be opening an iframe showing the user’s C: drive (or whatever) but even if that’s possible nowadays (could be blocked for security reasons, haven’t tried in a long time) it will be impossible for your web site to communicate with the iframe (again for security reasons).
What do you need this for?
Folder Choose in Html
you can see the folder name in alert when select a file
How to get full path of selected file on change of input type=‘file’ using javascript, jquery-ajax?
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);
>);
edit: If you need the file’s path for reading a file you can use the FileReader API instead. Here is a related question on SO: Preview an image before it is uploaded.
HTML multi-file input to get directory (Electon app)
The highest hierarchy you can get via this input and JavaScript is the top-most folder-name within the relative path – the one the user has chosen.
In your given example, this is assumed to be foo or bar .
⚠️ You will not get the absolute path (because this information is hidden, also for privacy/security reasons).
How to get path segments
Use string property webkitRelativePath and split-of the substring until first occurrence of path-separator / .
See also
- Get folder name on selection of folder from input field, already answered question
- MDN reference documentation webkitdirectory input with example
[html] How to get folder directory from HTML input type «file» or any other way?
So I have a basic form input with the type «file» however I want the user to be able to select a folder location and not a file.
How can I get this input to select a folder and not a file, or is there another way to do it?
This question is related to html file input directory
The answer is
Stumbled on this page as well, and then found out this is possible with just javascript (no plugins like ActiveX or Flash), but just in chrome:
Basically, they added support for a new attribute on the file input element «webkitdirectory». You can use it like this:
It allows you to select directories. The multiple attribute is a good fallback for browsers that support multiple file selection but not directory selection.
When you select a directory the files are available through the dom object for the control (document.getElementById(‘ctrl’)), just like they are with the multiple attribute. The browsers adds all files in the selected directory to that list recursively.
You can already add the directory attribute as well in case this gets standardized at some point (couldn’t find any info regarding that)
You’re most likely looking at using a flash/silverlight/activeX control. The control doesn’t handle that.
If you don’t mind the user selecting a file as a means to getting its directory, you may be able to bind to that control’s change event then strip the filename portion and save the path somewhere—but that’s about as good as it gets.
Keep in mind that webpages are designed to interact with servers. Nothing about providing a local directory to a remote server is «typical» (a server can’t access it so why ask for it?); however files are a means to selectively passing information.
Eventhough it is an old question, this may help someone.
We can choose multiple files while browsing for a file using «multiple»