为什么要在服务器端显示文件/文件夹对话框?
我正在构建一个旨在本地运行的项目(节点服务器端部分和浏览器中的客户端),我希望能够选择一个路径,将其添加到某个列表或JSON 文件,然后在其中维护一些项目(webpack'ing、读取文件、通过express 提供服务等)。
主要仅供个人使用,无论如何,现在。
我要求通过 Node 而不是浏览器执行此操作的原因是这样我可以以某种方式绕过现代浏览器中的安全隐患,即在选择文件夹时防止显示客户端上的完整本地文件夹路径(从
<input>
标签)。
不仅如此,我还:
我只需要:
以这个
input
标签为例:
<input id="open-project" type="file" />
这将导致这种类型的弹出窗口,这非常适合挖掘文件夹、粘贴部分路径以快速导航到您需要的位置、转到快速访问/收藏夹等...
但它的目的是选择文件,没有暴露路径,没有任何有用的东西可以传递到服务器。
但是...
如果你把它切换到这个...
<input id="open-project" type="file" webkitdirectory directory />
您最终会看到这个可怕的对话框,它假设您要上传文件夹中包含的所有文件。
所以看起来
<input>
并不是真正的出路。
也许有一个现有的模块可以在服务器端执行此操作?这样我就可以:
或者...
在浏览器中创建一个...树视图...与节点端来回通信以挖掘本地文件系统...
有什么建议吗?
我通过生成一个子 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
使用child_process调用外部程序
zenity --title="open file" --file-selection
zenity --title="save file" --file-selection --save --filename=asdf.txt
zenity --title="open directory" --file-selection --directory
kdialog --getopenfilename
kdialog --getsavefilename
kdialog --getexistingdirectory
dialogbox <<<'add label "asdf" msg; add pushbutton &Ok okay apply exit'