【问题标题】:Java Eclipse upload image to image folder within packageJava Eclipse将图像上传到包内的图像文件夹
【发布时间】:2020-03-10 19:54:49
【问题描述】:

我正在使用 Swing Jframe 在 Eclipse 中工作。我目前有一个上传按钮,单击该按钮时,我需要它允许用户浏览图像并将其上传(技术上复制并重命名)到我的 Java 项目中名为图像的文件夹中。 稍后我将引用文件路径并显示图像。任何帮助都会很棒!

    JButton uploadButton = new JButton("Upload...");
    uploadButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            //TODO
        }
    });
    uploadPanel.add(uploadButton, BorderLayout.SOUTH);
    return uploadPanel;

【问题讨论】:

  • “任何帮助都会很棒!” 任何与什么相关的帮助?我不确定你的问题是什么?或者如果它与如何复制图像、如何重命名图像、如何查找图像或如何显示图像有关
  • @Frakcool 有关如何使用按钮上传图像并将其保存到与 java 项目相同的包中的文件夹的任何帮助。
  • 如需更好的帮助,请尽快发帖minimal reproducible example
  • 试试这个链接,它有很好的文件选择器示例docs.oracle.com/javase/tutorial/uiswing/components/…

标签: java eclipse swing jbutton image-uploading


【解决方案1】:

希望这有助于回答您的问题:)

// Choose file
JFileChooser fc = new JFileChooser();
int result = fc.showOpenDialog(null);

// Make sure that a file was chosen, else exit
if (result != JFileChooser.APPROVE_OPTION) {
    System.exit(0);
}

// Get file path
String path = fc.getSelectedFile().getAbsolutePath();

// Create folder "images" (variable success will be true if a folder was created and false if it did not)
File folder = new File("images");
boolean success = folder.mkdir();
// Get the destination of the folder and the new image (image.jpg will be the new name)
String destination = folder.getAbsolutePath() + File.separator + "img.jpg";

try {
    // Copy file from source to destination
    FileChannel source = new FileInputStream(path).getChannel();
    FileChannel dest = new FileOutputStream(destination).getChannel();
    dest.transferFrom(source, 0, source.size());

    // Close shit
    source.close();
    dest.close();

    System.out.println("Done");
} catch (IOException e) {
    e.printStackTrace();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-30
    • 1970-01-01
    • 1970-01-01
    • 2015-04-24
    • 2014-10-24
    • 2020-01-10
    相关资源
    最近更新 更多