对于我的项目,我正在创建一个费用管理系统。在一个地方,用户可以从本地磁盘中选择一个图像文件,并在添加新费用时将其作为附件添加。

单击“保存”按钮后,上传的图像应显示在jLabel中,然后应保存在项目文件夹中(例如,/ src / accounts / media),并且路径应保存在mysql数据库的varchar列中,以备后用恢复。

现在,我可以上传图像并在jLabel中显示该图像。

谁能帮我解决如何将图像文件保存在文件夹中以及如何在数据库中存储路径?

    JFileChooser chooser = new JFileChooser();

    FileFilter ft = new FileNameExtensionFilter("Image Files", "jpg", "png", "jpeg");
    //FileFilter ft2 = new FileNameExtensionFilter("PDF Files", "pdf");

    chooser.addChoosableFileFilter(ft);
    //chooser.addChoosableFileFilter(ft2);
    chooser.showOpenDialog(null);
    File f = chooser.getSelectedFile();
    filePath = f.getAbsolutePath().toString();

    BufferedImage img = null;
    try {
        img = ImageIO.read(new File(filePath));
    } catch (IOException e) {
        e.printStackTrace();
    }

    Image dimg = img.getScaledInstance(lblAttachment.getWidth(), lblAttachment.getHeight(), Image.SCALE_SMOOTH);


    ImageIcon icon = new ImageIcon(dimg);
    lblAttachment.setText("");
    lblAttachment.setIcon(icon);

最佳答案

要将文件复制到另一个位置,可以选择

Way1

Way2

要存储路径,请在文件路径列中写入插入查询(SQL):

prepareStatement  ps = conn.prepareStatement("INSERT INTO filePath VALUES(?, ?, ?)" );

         ps.setString(1,filePath);
         ps.set..
     //  conn, connection object


完整教程Here

编辑:

要将其保存在一些默认的Resources文件夹中,可以获取EG的路径:

public class ClassDemo {

  public static void main(String[] args) throws Exception {

    ClassDemo c = new ClassDemo();
    Class cls = c.getClass();

    // finds resource relative to the class location
    URL url = cls.getResource("file.txt");
    System.out.println("Value = " + url);

    // finds resource relative to the class location
    url = cls.getResource("newfolder/a.txt");
    System.out.println("Value = " + url);
  }
}

07-25 23:37
查看更多