KenobiBastila
KenobiBastila

Reputation: 721

Absolute path to a local file in the user computer

Is there local file manipulation that's been done with JavaScript that can actually get the absolute path to a file or folder when the user chooses with a directory or file picker?

Specifically, I'd like to read/show the ABSOLUTE PATH from a file and open the file if the user requests it. At this point I'm not worried about gaining permissions and am just assuming I already have full permissions to these files.

Upvotes: 1

Views: 1607

Answers (2)

hassen imache
hassen imache

Reputation: 1

you can do it following this method :

server.js :

app.get('/run-tkinter', (req, res) => {
  const pythonProcess = spawn('python', ['script.py']);
  let output = '';

  pythonProcess.stdout.on('data', (data) => {
    output += data.toString();
  });

  pythonProcess.stderr.on('data', (data) => {
    console.error(`Erreur: ${data}`);
  });

  pythonProcess.on('close', (code) => {
    if (code === 0) {
      res.json({ filePath: output.trim() });
    } else {
      res.json({ error: "Erreur lors de la sélection du fichier" });
    }
  });
});

python file script.py :

import tkinter as tk
from tkinter import filedialog

def select_file():
    root = tk.Tk()
    root.withdraw()  # Cache la fenêtre principale de Tkinter
    root.attributes("-topmost", True)  # Met la fenêtre de dialogue au premier plan
    file_path = filedialog.askopenfilename()  # Ouvre la boîte de dialogue
    root.destroy()  # Ferme proprement la fenêtre Tkinter
    return file_path

if __name__ == '__main__':
    file_path = select_file()
    if file_path:
        print(file_path)  # Le chemin sera capturé par Node.js
    else:
        print("Aucun fichier sélectionné")

and tsx file :

import axios from "axios";
import { useState } from "react";

function TK() {
  const [filePath, setFilePath] = useState<string | null>(null);

  const runTkinter = async () => {
    try {
      const response = await axios.get("http://localhost:5000/run-tkinter");
      const data = response.data;

      console.log("Réponse reçue:", data); // Pour le débogage

      if (data.filePath) {
        setFilePath(data.filePath);
        // alert(`Fichier sélectionné : ${data.filePath}`);
      } else {
        alert(data.message || "Aucun fichier sélectionné.");
      }
    } catch (error) {
      console.error("Erreur lors de l'exécution du script:", error);
      alert("Une erreur est survenue.");
    }
  };

  return (
    <div style={{ textAlign: "center", marginTop: "50px" }}>
      <h1>Exécuter Tkinter depuis React</h1>
      <button
        onClick={runTkinter}
        style={{ padding: "10px 20px", fontSize: "16px" }}
      >
        Séléctionner le fichier
      </button>
      {filePath && (
        <div>
          <p>
            <strong>Chemin du fichier :</strong> {filePath}
          </p>
        </div>
      )}
    </div>
  );
}

export default TK;

Upvotes: 0

Zac Anger
Zac Anger

Reputation: 7757

Not from the web browser, a website/app in a browser doesn't know much about the hosts it's hitting besides what the host/webserver tells it. You would have to build the path in the web server code and stick that into the site. If the files being served aren't somewhere under the web server root (like /var/www, or the project directory for something like a Python or Node server, etc.), it's considered unsafe to allow access to other paths, which is why paths absolute from the web server root are common, rather than absolute in terms of the host's storage.

Upvotes: 2

Related Questions