Results 1 to 9 of 9
- 02-15-2010, 12:20 PM #1
Senior Member
- Join Date
- Feb 2010
- Location
- Waterford, Ireland
- Posts
- 748
- Rep Power
- 4
Sending a File from Server to Client and saving the file to Clients computer
Hey I was hoping if somebody could take a look at my code and point me in the right direction. I want the server to send a file to the client and i want the client to be able to save the file to his machine in the given directory of filedialog. The file is sent by the server to the client and the client seems to write to the directory choosen and the right amount of bytes are written but the file is either corrupted or invalid format or something because it does not open. I can see it on my desktop and it is in jpg format but doesn't not open.:confused:
Anyway, any help is appreciated.:)
here is the server side:
<code>
public class FileServer {
private ServerSocket serv;
private Socket client;
private File myFile;
public FileServer(int port) throws Exception
{
serv=new ServerSocket(port);
while(true)
{
//wait for Connection
System.out.println("Waiting for connection on port "+port);
client=serv.accept();
sendFile();
}
}
public void sendFile() throws Exception
{
myFile=new File("img.jpg");
ObjectOutputStream oos=new ObjectOutputStream(client.getOutputStream());
oos.writeObject(myFile);
}
</code>
and here is the client side:
<code>
sock=new Socket(host,port);
System.out.println("Connection made (clientSide)");
//recieve the file
ObjectInputStream ois=new
ObjectInputStream(sock.getInputStream());
//read an object from the server
myfile=(File)ois.readObject();
byte[]b=new byte[(int)myfile.length()];
FileDialog choo=new FileDialog(myFrame,"Choose File Destination",FileDialog.SAVE);
choo.setDirectory(null);
choo.setFile("enter file name here");
choo.setVisible(true);
FileOutputStream fos=new FileOutputStream(choo.getDirectory()+choo.getFile( )+".jpg");
fos.write(b);
</code>
- 02-15-2010, 02:56 PM #2
Senior Member
- Join Date
- Dec 2009
- Location
- Belgrade, Serbia
- Posts
- 364
- Rep Power
- 4
What you actually doing is writing an empty file to client,
file has proper extension and its lenght is good but there is no content.
Reason for that is :
beacuse your byte array :Java Code:fos.write(b);
does not hold content of file at all, instead it is just as long as original !Java Code:byte[]b=new byte[(int)myfile.length()];
Use debugger to see this !
---
This :
...works fine if you have something like this in your code:Java Code:fos.write(b);
---Java Code:File file = new File("file.txt"); FileOutputStream fos=new FileOutputStream(file); String s ="Content fot text file"; byte b[] = str.getBytes(); fos.write(b); fop.close();
...but here is totally different story because you got your content inside:
myfile=(File)ois.readObject();
Print properties of this file to ouput to see what I mean
- 02-15-2010, 03:27 PM #3
Senior Member
- Join Date
- Dec 2009
- Location
- Belgrade, Serbia
- Posts
- 364
- Rep Power
- 4
...And now when you have deserialized original file on clients side :
there are a few ways to deal with.Java Code:myfile=(File)ois.readObject();
First thing rhat croseed my mind is copying it to location
that user choose with Save as dialog.
Hope this will help:
Client code:
iJava Code:mport java.awt.FileDialog; import java.awt.Frame; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.net.Socket; import java.net.UnknownHostException; public class FileServerClient3 { File myfile; Frame myFrame = new Frame(); public void receiveFileFromServer() throws ClassNotFoundException, IOException{ Socket sock = null; String host = "localhost"; int port = 9999; try { sock = new Socket(host, port); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } System.out.println("Connection made (clientSide)"); //recieve the file ObjectInputStream ois = null; try { ois = new ObjectInputStream(sock.getInputStream()); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } /*file from server is deserialized*/ myfile=(File)ois.readObject(); /*deserialized file properties*/ System.out.println("AbsolutePath: " + myfile.getAbsolutePath()); System.out.println("FileName:" + myfile.getName() ); System.out.println("lenght" + myfile.length()); FileDialog choo = new FileDialog(myFrame,"Choose File Destination",FileDialog.SAVE); choo.setDirectory(null); choo.setFile("enter file name here"); choo.setVisible(true); String targetFileName = choo.getDirectory()+choo.getFile( )+".jpg" ; System.out.println("File will be saved to: " + targetFileName); copyBytes(myfile, targetFileName); }// private void copyBytes(File originalFile, String targetFileName) throws IOException { FileInputStream in = null; FileOutputStream out = null; in = new FileInputStream(originalFile); out = new FileOutputStream(targetFileName); int c; while ((c = in.read()) != -1) { out.write(c); } out.close(); in.close(); }// public static void main(String[] args) { FileServerClient3 client = new FileServerClient3(); try { client.receiveFileFromServer(); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } }// /
Server code:
Before you begin fix:Java Code:import java.io.File; import java.io.IOException; import java.io.ObjectOutputStream; import java.net.ServerSocket; import java.net.Socket; public class FileServer { private ServerSocket serv; private Socket client; private File myFile; public FileServer(int port, String fileName) throws IOException { serv = new ServerSocket(port); myFile = new File (fileName); while(true) { //wait for Connection System.out.println("Waiting for connection on port "+port); client=serv.accept(); sendFile(); } } public void sendFile() throws IOException { if (!myFile.exists()) { System.out.println("File doesn not exist!"); System.exit(-1); } //file do exist System.out.println("AbsolutePath:" + myFile.getAbsolutePath()); System.out.println("length: " + myFile.length()); if (myFile.exists()) { ObjectOutputStream oos=new ObjectOutputStream(client.getOutputStream()); oos.writeObject(myFile); } } public static void main(String[] args) { int port = 9999; String fileName = "C:\\workspace\\Sve\\src\\feb15\\ab.jpg"; try { FileServer fs = new FileServer(port, fileName); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }catch (Exception e){ e.printStackTrace(); } } }///
IP, port, filePaths
some this will help :)
cheers!
- 02-15-2010, 04:45 PM #4
Senior Member
- Join Date
- Feb 2010
- Location
- Waterford, Ireland
- Posts
- 748
- Rep Power
- 4
oh brilliant! thanks alot!!
I figured it out another way not using objectoutputs and input streams but I wanted to be able to determine the file type and length, seems like using ObjectInput streams is the best way for this.
thanks again for the help much appreciated.
- 02-15-2010, 07:52 PM #5
Senior Member
- Join Date
- Dec 2009
- Location
- Belgrade, Serbia
- Posts
- 364
- Rep Power
- 4
;)
welcome to the forum!
- 02-16-2010, 06:43 PM #6
Member
- Join Date
- Feb 2010
- Posts
- 2
- Rep Power
- 0
Hi,
Can anyone provide me a java code to transfer a multimedia file over a LAN.
- 02-16-2010, 10:45 PM #7
Senior Member
- Join Date
- Dec 2009
- Location
- Belgrade, Serbia
- Posts
- 364
- Rep Power
- 4
- 02-17-2010, 03:03 PM #8
Senior Member
- Join Date
- Feb 2010
- Location
- Waterford, Ireland
- Posts
- 748
- Rep Power
- 4
Ok i decided to try and develop it a bit more and began a multithreaded chat system that also has file sending capabilities. Im running into problems with sending files. The file sender(client) freezes after sending the file to the server. If i close the outputstream of the client, the client unfreezes but this leads to the client socket being disconnected. It is strange because sending messages back and forth between client-->server-->other clients works without freezing.
Could anybody point me in the right direction i.e. stop the freezing of client
ServerSetup:
FileChatServerDealer:Java Code:while(true) { //Wait for Connection client=serv.accept(); //if connection is made put details in server frame area.append("Connection Made From "+client.getInetAddress().getHostAddress()+"\n"); area.append("Connection Start Time: "+date); //add client to ArrayList<Socket> sockList.add(client); System.out.println("There are now "+sockList.size()+" clients"); //let FileChatServerDealer deal with this client new FileChatServerDealer(this,client); } public void sendFile(File file,Socket c,String ext,String size) throws Exception { for(int i=0;i<sockList.size();i++) { if(sockList.get(i).equals(c)) { System.out.println("Skipping file sender"); //skip the sender of the file } else{ System.out.println("Server is sending file back"); date=new Date(); area.append(date+"Server is sending file back to "+sockList.get(i).getInetAddress().getHostAddress()+"\n"); dos=new DataOutputStream(sockList.get(i).getOutputStream()); dos.writeUTF("2"); dos.writeUTF(ext); dos.writeUTF(size); if(file.exists()) { dis=new DataInputStream(new FileInputStream(file)); byte []b=new byte[(int)file.length()]; System.out.println(file.length()); int in; while((in=dis.read(b))!=-1) { dos.write(b,0,in); } dos.flush(); }else{ System.out.println("File doesnt exist"); } } } }
Client FileSendingSetup:Java Code:public class FileChatServerDealer extends Thread{ private FileChatServer fcs; private Socket s; private File theFile; public FileChatServerDealer(FileChatServer fcs, Socket s) { this.fcs=fcs; this.s=s; start(); } public void run() { try{ while(true) { DataInputStream dis=new DataInputStream(s.getInputStream()); String requestType=dis.readUTF(); if(requestType.equals("2")) { String ext=dis.readUTF(); String size=dis.readUTF(); long fSize=Long.parseLong(size); System.out.println("Server is dealing with File send"); byte[]b=new byte[(int)fSize]; String path="C:\\blablabla"+ext; FileOutputStream fos=new FileOutputStream(path); int in; while ((in = dis.read(b)) != -1){ System.out.println("Writing file to disk.."); fos.write(b,0,in); } fos.flush(); System.out.println("Ok Server got the file"); theFile=new File(path); fcs.sendFile(theFile,s,ext,size); } else if(requestType.equals("3")) { System.out.println("Server is finding online users"); fcs.findAllUsers(s); } else if(requestType.equals("0")) { System.out.println("Server has username"); dis=new DataInputStream(s.getInputStream()); String user=dis.readUTF(); fcs.addUser(user); } else{ System.out.println("Server is Dealing with message"); dis=new DataInputStream(s.getInputStream()); String mess=dis.readUTF(); fcs.sendMessage(mess); } }//end or while loop }catch(Exception e){ //do nothing } } }
and the thread for each clientJava Code:public void sendFileToServer(File theFile,String ext,long fileSize) throws Exception { DataOutputStream dout=new DataOutputStream(client.getOutputStream()); DataInputStream dinny=new DataInputStream(new FileInputStream(theFile)); dout.writeUTF("2"); dout.writeUTF(ext); String sizer=Long.toString(fileSize); dout.writeUTF(sizer); byte b[]=new byte[(int) fileSize]; int inny; while((inny=dinny.read(b))!=-1) { dout.write(b,0,inny); } dout.flush(); }
Java Code:public class DealWithConnection extends Thread{ private FileChatClient fcc; private Socket s; private String msg; public DealWithConnection(FileChatClient fcc,Socket s) { this.fcc=fcc; this.s=s; start(); } public void run() { try{ //1 is message 3 is find users while(true) { DataInputStream dis=new DataInputStream(s.getInputStream()); FileOutputStream fos=null; String incomingType=dis.readUTF(); if(incomingType.equals("1")) { String mesRec=dis.readUTF(); fcc.appendMessage(1); } else if(incomingType.equals("3")) { String mesRec=dis.readUTF(); fcc.appendMessage(3); } else{ System.out.println("Client is getting file"); //recieve the file String ext1=dis.readUTF(); String fsize=dis.readUTF(); long fileSi=Long.parseLong(fsize); byte[]b=new byte[(int)fileSi]; String path=fcc.chooseDestination(); fos=new FileOutputStream(path+ext1); int in; while ((in = dis.read(b)) != -1){ System.out.println("Client saving file.."); fos.write(b,0,in); } fos.flush(); fcc.confirmSave(path); } }//end of while }catch(Exception e){} }//end of void run() }
- 02-18-2010, 12:54 PM #9
Senior Member
- Join Date
- Feb 2010
- Location
- Waterford, Ireland
- Posts
- 748
- Rep Power
- 4
Is it possible to write a file to a clients computer without using any kind of InputStream first?
for example: I want the server to send a client a file. The server recieves the file from another clients machine. So, the file path is from the clients machine that sent the file. Now the problem I have is that the recieving client has a file with a path that is from another computer. So when the receiving client tries to read it with an InputStream the file path doesn't exist on his machine.
Quick diagram:
client(file sender)--->server--->Client(file Receiver)
I realise I can make this work without using ObjectInput/Output Streams and write the file byte by byte to the server then have the server write byte by byte to the receiving client. I was just wondering if it is possible to save a file without using the original path using ObjectOutputStream. Or is it possible to read a file sent by an ObjectOutputStream without needing the original path.Java Code:System.out.println("Client is getting file"); //recieve the file String fileType=dis.readUTF(); String fsize=dis.readUTF(); ObjectInputStream ois=new ObjectInputStream(s.getInputStream()); File file; file=(File)ois.readObject(); System.out.println("File length: "+file.length()); //this is where the trouble is, the FileInputStream has a path that is //not recognised by the receiving client. Atleast I'm sure that is what is //happening FileChannel src=new FileInputStream(file).getChannel(); //client selects a target path using filedialog String path=fcc.chooseDestination(); FileChannel dest=new FileOutputStream(path+fileType).getChannel(); dest.transferFrom(src, 0, src.size()); System.out.println("Client has saved File"); fcc.confirmSave(path);
Any help is appreciated, thanks.
Similar Threads
-
Sending image file over serversocket to browser client
By maheshsk in forum NetworkingReplies: 3Last Post: 12-10-2009, 03:49 PM -
Sending image file over serversocket to browser client
By maheshsk in forum Advanced JavaReplies: 1Last Post: 12-10-2009, 02:40 PM -
Sending image file over serversocket to browser client
By maheshsk in forum Web FrameworksReplies: 1Last Post: 12-10-2009, 02:39 PM -
how to send a file from server to client and client saves the file?
By KoolCancer in forum New To JavaReplies: 3Last Post: 07-29-2009, 04:52 AM -
Sending a .Doc file from client to a server through socket
By amita_k29 in forum NetworkingReplies: 1Last Post: 02-10-2009, 09:16 AM


LinkBack URL
About LinkBacks


Bookmarks