我有两个项目;一个用于我的服务器,另一个用于我的客户端,我能够轻松地将图像发送到服务器。但是我想知道,当我按下在客户端GUI上创建的下载按钮时,如何将刚刚发送到服务器的映像重新下载回客户端?我的代码是用Java编写的。
非常感谢
这是我的服务器处理程序
String fileName; fileName = "RecievedImageoutreach1.jpg"; DataOutputStream dout = new DataOutputStream(sock.getOutputStream()); //Coding for image transfer int flag=0,i; String extn=""; for(i=0; i<fileName.length(); i++) { if(fileName.charAt(i)=='.' || flag==1) { flag=1; extn += fileName.charAt(i); } } if(extn.equals(".jpg") || extn.equals(".gif")) { try{ File file = new File(fileName); FileInputStream fin = new FileInputStream(file); dout.writeUTF(fileName); byte[] readData = new byte[1024]; while((i = fin.read(readData)) != -1) { dout.write(readData, 0, i); } //ta.appendText("\nImage Has Been Sent"); dout.flush(); fin.close(); }catch(IOException ex) {System.out.println("Image ::"+ex);} } }
这是我的客户
public void download() throws IOException { // Get input from the server DataInputStream dis = new DataInputStream (sock.getInputStream()); String str,extn = ""; str = dis.readUTF(); int flag=0,i; for(i=0;i<str.length();i++) { if(str.charAt(i)=='.' || flag==1) { flag=1; extn+=str.charAt(i); } }
// ***阅读图片*** * //
if(extn.equals(".jpg") || extn.equals(".gif")) { File file = new File("Downloaded"+str); FileOutputStream fout = new FileOutputStream(file); //receive and save image from client byte[] readData = new byte[1024]; while((i = dis.read(readData)) != -1) { fout.write(readData, 0, i); if(flag==1) { ta.append("Image Has Been Downloaded"); flag=0; } } fout.flush(); fout.close(); } }
但是运行时什么也没发生?我已经链接了单击按钮时要运行的客户端方法。
我会做这样的事情:
//服务器处理程序
File file = new File(fileName); FileInputStream fin = new FileInputStream(file); // dout.writeUTF(fileName); byte[] readData = new byte[1024]; fin.read(readData); fin.close(); dout.write(readData, 0, readData.length); dout.flush(); /* while((i = fin.read(readData)) != -1) { dout.write(readData, 0, i); }*/ //ta.appendText("\nImage Has Been Sent"); dout.flush(); fin.close(); }catch(IOException ex) {System.out.println("Image ::"+ex);} }
//接收图片
if(extn.equals(".jpg") || extn.equals(".gif")) { //give path to new file File file = new File(".//Downloaded"+str); FileOutputStream fout = new FileOutputStream(file); //receive and save image from client byte[] readData = new byte[1024]; int offset =0; while((i = dis.read(readData,0,readData.length-offset)) != -1){ offset += i; } fout.write(readData, 0, readData.length); if(flag==1) { ta.append("Image Has Been Downloaded"); flag=0; } fout.flush(); fout.close(); } }