如何从NodeJS(服务器端,而不是浏览器)打开“选择文件夹”对话框?

时间:2018-08-02 14:01:41

标签: javascript node.js windows path openfiledialog

  

您为什么要在服务器端显示文件/文件夹对话框?

     

我正在构建一个打算在本地运行的项目(浏览器中的Node服务器端部分和客户端端),在这里我希望能够选择路径,并将其添加到一些列表或JSON文件,然后在其中维护一些项目(Webpack打包,读取文件,通过Express投放等)。

     

大多数情况下仅供个人使用,无论如何 now

我要求通过Node而不是浏览器来执行此操作的原因是,这样我就可以以某种方式解决现代浏览器中的安全隐患,该隐患可以防止在选择文件夹后在客户端显示完整的本地文件夹路径(来自<input>标签)。

不仅如此,我还:

  • 不需要上传任何文件,或者
  • 不需要选定文件夹中包含的文件列表。

我只需要:

  • 以一种用户友好的方式选择文件夹的方法,然后...
  • 提交它到服务器的路径
  • (或让服务器提示,并将其存储在某个地方)。

以这个input标签为例:

<input id="open-project" type="file" />

这将导致这种类型的弹出窗口,非常适合于浏览文件夹,粘贴部分路径以快速导航至您需要的位置,转到“快速访问/收藏夹”等...

Shows the Open file dialog

但这是选择文件的目的,没有暴露任何路径,没有任何有用的信息可以传递到服务器。

但是...

如果将其切换到此...

<input id="open-project" type="file" webkitdirectory directory />

您最终看到一个可怕的对话框,假定您要上载文件夹中包含的所有文件。

enter image description here

enter image description here


所以看来<input>并不是真正的方法。

也许在服务器端有一个现有的模块可以执行此操作?这样我可以:

  • 例如通过AJAX从客户端“调用”它
  • 然后会在服务器上触发它
  • 然后向我显示文件夹选择提示

或者...

在浏览器中制作一个...树状视图...与节点侧来回通信以挖掘本地文件系统...

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

我通过产生一个子级powershell进程并将该值传回给父级来实现。这仅适用于Windows服务器,但类似的方法应适用:

let psScript = `
Function Select-FolderDialog
{
    param([string]$Description="Select Folder",[string]$RootFolder="Desktop")

 [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") |
     Out-Null     

   $objForm = New-Object System.Windows.Forms.FolderBrowserDialog
        $objForm.Rootfolder = $RootFolder
        $objForm.Description = $Description
        $Show = $objForm.ShowDialog()
        If ($Show -eq "OK")
        {
            Return $objForm.SelectedPath
        }
        Else
        {
            Write-Error "Operation cancelled by user."
        }
    }

$folder = Select-FolderDialog # the variable contains user folder selection
write-host $folder
`

从本质上讲,这是您需要提示输入文件夹位置,然后将其写入主机的脚本(类似于console.log)

然后您需要执行此脚本并处理输出:

var spawn = require("child_process").spawn,child;
child = spawn("powershell.exe",psScript);
child.stdout.on("data",function(data){
    console.log("Powershell Data: " + data);
});
child.stderr.on("data",function(data){
    //this script block will get the output of the PS script
    console.log("Powershell Errors: " + data);
});
child.on("exit",function(){
    console.log("Powershell Script finished");
});
child.stdin.end(); //end input