user12358450
user12358450

Reputation:

How just select directory not file?

I using js to create my form, my problem is how to just select directory, not file?

Belows is my coding:

const realFileBtn = document.getElementById("real-file");
const customBtn = document.getElementById("custom-button");
const customTxt = document.getElementById("custom-text");

customBtn.addEventListener("click", function() {
  realFileBtn.click();
});

realFileBtn.addEventListener("change", function() {
  if (realFileBtn.value) {
    customTxt.innerHTML = realFileBtn.value;
  } else {
    customTxt.innerHTML = "No file chosen, yet.";
  }
});
<input type="file" id="real-file" hidden="hidden" />
<button type="button" id="custom-button">CHOOSE A FILE</button>
<span id="custom-text">No file chosen, yet.</span>

Below is my output:

Output 1

Actually I want the output not to select the file, just select the folder, because the next step I need store file in this folder directory.

If success the output is folder directory name is:

C:\Staff Import Folder\Source

Hope someone can help me solve this problem. Thanks.

Upvotes: 0

Views: 2915

Answers (2)

Kaiido
Kaiido

Reputation: 136638

In newest browsers, you can select a directory content with the webkitdirectory attribute of the <input type="file"> element, as being defined by Files and Directories entries API, but I fear this will be deceptive to you since it will only select all the files in this directory (and its sub-folders). There is currently no way to navigate this directory from here.

We should be able to navigate such directory, by looking at the webkitEntries IDL attribute, but currently browsers only populate this from a drop event. You can see a demo in this Q.A.

inp.onchange = (e) => {
  console.log( inp.webkitEntries ); // []
  console.log( [...inp.files].map( file => file.name ) );
};
<input type="file" webkitdirectory id="inp">

But even then, while you'll be able to navigate that directory, you still won't be able to set anything on the FileSystem. Web scripts simply don't have the authorization to write anything on the disk, except in sand-boxed areas like IndexedDB.

Upvotes: 2

Abdelrahman Gobarah
Abdelrahman Gobarah

Reputation: 1589

https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/webkitdirectory

document.getElementById("filepicker").addEventListener("change", function(event) {
  let output = document.getElementById("listing");
  let files = event.target.files;

  for (let i = 0; i < files.length; i++) {
    let item = document.createElement("li");
    item.innerHTML = files[i].webkitRelativePath;
    output.appendChild(item);
  };
}, false);
<input type="file" id="filepicker" name="fileList" webkitdirectory multiple />
<ul id="listing"></ul>

Upvotes: 1

Related Questions