2014-08-29 103 views
1

對於我的項目,我創建了費用管理系統。在添加新費用時,用戶可以從本地磁盤選擇映像文件並將其添加爲附件。將圖像保存到特定的文件夾中,並在mysql中存儲路徑以便稍後顯示

上傳的圖像應該顯示在一個jLabel中,然後應保存在項目文件夾(比如/ src/accounts/media)中,點擊保存按鈕時,路徑應保存在varchar列的內部mysql數據庫供以後檢索。

現在,我可以上傳圖像並在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); 
+0

[保存爲.jpg文件圖像的可能重複:Java的](http://stackoverflow.com/questions/15095934/saving-an-image-to-jpg-file-java) – ControlAltDel 2014-08-29 16:52:23

回答

0

要文件複製到另一個位置,你可以選擇任何

Way1

Way2

要保存的路徑,使文件的路徑欄寫插入查詢(SQL):

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

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

完整教程Here

編輯:

將其保存在你一些默認的資源文件夾,您可以獲取路徑,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); 
    } 
} 
+0

謝謝!你能解釋我如何使用相對路徑選項將圖像保存到項目文件夾中嗎?因爲項目位置可以變化,我需要一些可移植性選項。 我想複製文件夾/ src/exp/resources中的圖像 – FireDrakon 2014-08-31 06:49:34

+0

使用您的文件夾的完整路徑。可以說'C://用戶// U_name // MyDocuments // NetBeansProject ..... ProjectFolderName' .. – 2014-08-31 06:54:41

+0

嗯..但是如果項目的位置可以改變呢?如果我可以使用像/ src/resources這樣的相對路徑,無論項目位於何處,保存圖像都會更容易。對? – FireDrakon 2014-08-31 07:23:19

相關問題