用户计算机中本地文件的绝对路径

问题描述 投票:0回答:2

是否有使用 JavaScript 完成的本地文件操作,当用户使用目录或文件选择器进行选择时,实际上可以获取文件或文件夹的绝对路径?

具体来说,我想从文件中读取/显示绝对路径,并在用户请求时打开该文件。此时,我并不担心获得权限,只是假设我已经拥有这些文件的完全权限。

javascript html file-access
2个回答
2
投票

不是来自网络浏览器,浏览器中的网站/应用程序除了主机/网络服务器告诉它的信息之外,并不了解它所访问的主机。您必须在 Web 服务器代码中构建路径并将其粘贴到站点中。如果所提供的文件不在 Web 服务器根目录下的某个位置(例如 /var/www,或者 Python 或 Node 服务器等的项目目录),则允许访问其他路径被认为是不安全的,即为什么来自网络服务器根的绝对路径很常见,而不是主机存储方面的绝对路径。


0
投票

您可以按照以下方法进行:

服务器.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 文件 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é")

和 tsx 文件:

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;
© www.soinside.com 2019 - 2024. All rights reserved.