java客户端文件的上传和下载

1 //上传 2 public JTable upload(String id){ 3 JTable table=new JTable(); 4 System.out.println("上传"); 5 JFileChooser fileChooser=new JFileChooser(); 6 fileChooser.setDialogTitle("文件上传"); 7 fileChooser.showOpenDialog(null); 8 fileChooser.setVisible(true); 9 String srcPath=fileChooser.getSelectedFile().getAbsolutePath(); 10 System.out.println(srcPath); 11 12 String destFile="contract/"+id+".pdf"; 13 System.out.println(destFile); 14 try{ 15 FileInputStream in=new FileInputStream(srcPath); 16 FileOutputStream out=new FileOutputStream(destFile); 17 byte[] buf=new byte[8*1024]; 18 int b; 19 while((b=in.read(buf, 0, buf.length))!=-1){ 20 out.write(buf,0,b); 21 out.flush();//最好加上 22 } 23 System.out.println("上传成功!!"); 24 in.close(); 25 out.close(); 26 //在数据库里更新 27 //sql语句肯定是在这边传,因为这边是需求满足 28 //直接在数据库里面改数据,在这边刷新数据就可以了 29 JOptionPane.showMessageDialog(this,"上传成功"); 30 table=this.refresh(); 31 32 } 33 catch (Exception ex3){ 34 ex3.printStackTrace(); 35 } 36 return table; 37 }

1 public JTable download(String id){ 2 System.out.println("下载"); 3 4 JTable table=new JTable(); 5 6 JFileChooser fileChooser=new JFileChooser(); 7 fileChooser.setDialogTitle("选择要存放下载文件的位置"); 8 fileChooser.showOpenDialog(null); 9 fileChooser.setVisible(true); 10 String destPath=fileChooser.getSelectedFile().getAbsolutePath(); 11 System.out.println(destPath); 12 13 String endFileName=".pdf"; 14 if(!destPath.endsWith(endFileName)){ 15 destPath+=endFileName; 16 } 17 18 String srcFile="contract/"+id+".pdf"; 19 20 String destFile=destPath; 21 System.out.println(destFile); 22 try{ 23 FileInputStream in=new FileInputStream(srcFile); 24 FileOutputStream out=new FileOutputStream(destFile); 25 byte[] buf=new byte[8*1024]; 26 int b; 27 while((b=in.read(buf, 0, buf.length))!=-1){ 28 out.write(buf,0,b); 29 out.flush();//最好加上 30 } 31 System.out.println("下载成功!!"); 32 in.close(); 33 out.close(); 34 JOptionPane.showMessageDialog(this,"下载成功"); 35 //下载操作不需要连数据库不需要刷新 36 table=this.refresh(); 37 } 38 catch (Exception ex3){ 39 ex3.printStackTrace(); 40 } 41 return table; 42 }