Multiple File Uploader Java

青春壹個敷衍的年華 提交于 2019-12-14 03:21:17

问题


I've created a program to upload images from one device to another. As it stands, the program only allows the user to upload one file at a time. If I wanted to edit the program to allow the user to upload several files at once, what would be the best way of doing it.

String source1 = source.getSelectedFile().getPath();
System.out.println("Source1: " + source1);
String nwdir1 = nwdir.getSelectedFile().getPath() + "\\" + filename;
System.out.println("nwdir1: " + nwdir1);

Path source = Paths.get(source1);
Path nwdir = Paths.get(nwdir1);

try {
    Files.copy(source, nwdir);

I've noticed you can do .getSelectedFiles(), but as that doesn't allow .getPath() im unsure how to continue. Assuming you can do this:

File[] source1 = source.getSelectedFiles();

How would I go about doing the second line:

String nwdir1 = nwdir.getSelectedFile().getPath() + "\\" + filename;

When I replace the line with the File array (shown above), I get an error on lines:

Path source = Paths.get(source1);
Path nwdir = Paths.get(nwdir1);

回答1:


File.listFiles or File.listFiles(FileFilter)

Multi file selection

Sorry, that's what I thought you wanted, but you're using the JFileChooser to select a directory so I assumed you want to do a directory listing :P

Set the JFileChooser to allow multiple selections using setMultiSelectionEnabeld. You'll probably want to set the file selection mode to JFileChooser.FILES_ONLY or JFileChooser.FILES_AND_DIRECTORIES if you still want them to be able to select directories.

You will probably also want to set the file filter to allow the dialog to filter the directories contents, restricting what the user can select, for simplicity sake, take a look at FileNameExtensionFilter

UPDATED

JFileChooser chooser = new JFileChooser();
chooser.setMultiSelectionEnabled(true);
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
FileNameExtensionFilter filter = new FileNameExtensionFilter("Images", "png", "jpg", "jpeg");
chooser.setFileFilter(filter);

switch (chooser.showOpenDialog(null)) {

    case JFileChooser.APPROVE_OPTION:

        String currentPath = chooser.getCurrentDirectory().getPath();
        File[] files = chooser.getSelectedFiles();

        if (files.length > 0) {

            System.out.println("You have choosen " + files.length + " from " + currentPath);

        } else {

            System.out.println("You didn't selected anything");

        }

        break;

}



回答2:


Use FileUtils from apache commons library. Very powerful and useful. You can even specify which file formats you want to copy etc.



来源:https://stackoverflow.com/questions/11939933/multiple-file-uploader-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!