浏览按钮以选择目录

时间:2013-08-20 10:16:26

标签: java applet

我想在我的网页中创建一个浏览按钮来选择目录而不是文件。我知道输入类型文件在这里不起作用,但有没有办法用Javascript来做。我想获得客户端机器的文件路径,这在IE中是可能的,但其他浏览器不支持,但这对我来说没问题。

我遇到的问题是如何在按钮中获取文件目录。

下面是我用来从浏览器调用applet的代码但是我从bootclasspath中检测到:C:\ PROGRA~1 \ Java \ jre7 \ lib \ deploy.jar错误在浏览器中。我使用Java 1.5编译了类文件

<applet code="com.life.draw.BrowsePage.class"></applet>

代码

public class BrowsePage extends JApplet {
@Override
public void paint(Graphics g) {
    // TODO Auto-generated method stub
    JFileChooser chooser = new JFileChooser();
    chooser.setCurrentDirectory(new java.io.File("."));
    chooser.setDialogTitle("Browse the folder to process");
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    chooser.setAcceptAllFileFilterUsed(false);

    if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
        System.out.println("getCurrentDirectory(): "+ chooser.getCurrentDirectory());
        System.out.println("getSelectedFile() : "+ chooser.getSelectedFile());
    } else {
        System.out.println("No Selection ");
    }
}
}

2 个答案:

答案 0 :(得分:3)

为什么你用你的paint方法调用它?这可能是尝试创建新的窗口,每次applet都是painted

public void paint(Graphics g) {
    // TODO Auto-generated method stub
    JFileChooser chooser = new JFileChooser();
    /*...*/

相反,在JButton方法中创建init并附加ActionListener ...

public void init() {
    setLayout(new GridBagLayout());
    JButton browse = new JButton("...");
    browse.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            JFileChooser chooser = new JFileChooser();
            chooser.setCurrentDirectory(new java.io.File("."));
            chooser.setDialogTitle("Browse the folder to process");
            chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            chooser.setAcceptAllFileFilterUsed(false);

            if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
                System.out.println("getCurrentDirectory(): "+ chooser.getCurrentDirectory());
                System.out.println("getSelectedFile() : "+ chooser.getSelectedFile());
            } else {
                System.out.println("No Selection ");
            }
        }
    });
    add(browse);
}

您可能还想看看What Applets Can and Cannot Do

答案 1 :(得分:2)

在Web浏览器中获取本地浏览对话的唯一方法是使用<input type="file"/>,或使用Java Applet或Adobe Flash插件。没有内置的方法可以在Web浏览器中从JS获取目录引用。

此外,您无法读取客户端硬盘的内容,甚至无法通过JavaScript启动浏览对话。如果你能够,它会带来相当大的安全问题。

在阅读目录时,请查看以下帖子:

Local file access with javascript

Getting content of a local file without uploading

Javascript: Getting the contents of a local server-side file

听起来,你需要编写一个flash插件,让你在本地选择一个目录。但是,在下载插件时,您的用户将收到安全警告。

编辑:

还有基于webkit的方法,但这只适用于基于webkit的浏览器(Chrome,Safari等)。

How do I use Google Chrome 11's Upload Folder feature in my own code?