Select only folder - HTML

Asked

Viewed 504 times

-1

How can I make a input[type="file"] select only folder, instead of files?

I used the dial:
<input type="file" multiple webkitdirectory>


But apparently, it selects the files from the folder. Displaying: inserir a descrição da imagem aqui


  • But while accessing the folder, you will be selecting the internal files as well.

1 answer

1


Solution

You can take the full path of a file and just remove the file name

Code

The code below is commented explaining its operation.

$('[type="file"]').on("change", function(event) {

  //Pega apenas um arquivo
  let file = event.target.files[0];
  
  //Pega o caminho do arquivo
  let caminho = file.webkitRelativePath;
  
  //Desmonta o caminho em um array
  let arrayPath = caminho.split('/');
  
  //Remove só o arquivo do caminho
  arrayPath.pop();
  
  //Controi o caminho denovo
  console.log(arrayPath.join('/'));
  
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" id="ctrl" webkitdirectory directory multiple/>

Helping

How to get Folder directory from HTML input type "file" or any other way?

HTMLInputElement.webkitdirectory

Important remark

If your project is a web application, although you can get the folder path, you can’t use it to manipulate in the future.

If you need these files, you will have to save to your server, and then manipulate, since your server will no longer have access to your user’s folder.

  • Very good, thank you. I found it in a similar way, but yours is better. Is there any way I can display the directory? For example: "C:/test-folder/folder-one" instead of just the folder, as "folder-one".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.