Results 1 to 9 of 9
  1. #1
    al_Marshy_1981 is offline Senior Member
    Join Date
    Feb 2010
    Location
    Waterford, Ireland
    Posts
    748
    Rep Power
    5

    Default 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>

  2. #2
    FON
    FON is offline Senior Member
    Join Date
    Dec 2009
    Location
    Belgrade, Serbia
    Posts
    368
    Rep Power
    5

    Default

    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 :

    Java Code:
    fos.write(b);
    beacuse your byte array :

    Java Code:
    byte[]b=new byte[(int)myfile.length()];
    does not hold content of file at all, instead it is just as long as original !

    Use debugger to see this !

    ---

    This :

    Java Code:
    fos.write(b);
    ...works fine if you have something like this in your code:

    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

  3. #3
    FON
    FON is offline Senior Member
    Join Date
    Dec 2009
    Location
    Belgrade, Serbia
    Posts
    368
    Rep Power
    5

    Default

    ...And now when you have deserialized original file on clients side :

    Java Code:
     myfile=(File)ois.readObject();
    there are a few ways to deal with.

    First thing rhat croseed my mind is copying it to location
    that user choose with Save as dialog.

    Hope this will help:

    Client code:

    i
    Java 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:

    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();
    		}
    	}
    	
    }///
    Before you begin fix:
    IP, port, filePaths

    some this will help :)

    cheers!

  4. #4
    al_Marshy_1981 is offline Senior Member
    Join Date
    Feb 2010
    Location
    Waterford, Ireland
    Posts
    748
    Rep Power
    5

    Default

    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.

  5. #5
    FON
    FON is offline Senior Member
    Join Date
    Dec 2009
    Location
    Belgrade, Serbia
    Posts
    368
    Rep Power
    5

    Default

    ;)

    welcome to the forum!

  6. #6
    chethukt is offline Member
    Join Date
    Feb 2010
    Posts
    2
    Rep Power
    0

    Default

    Hi,

    Can anyone provide me a java code to transfer a multimedia file over a LAN.

  7. #7
    FON
    FON is offline Senior Member
    Join Date
    Dec 2009
    Location
    Belgrade, Serbia
    Posts
    368
    Rep Power
    5

    Default

    Quote Originally Posted by chethukt View Post
    Hi,

    Can anyone provide me a java code to transfer a multimedia file over a LAN.
    Well forum is not copy/paste code oriented,
    let us see your efforts first then we will be glad to help you

  8. #8
    al_Marshy_1981 is offline Senior Member
    Join Date
    Feb 2010
    Location
    Waterford, Ireland
    Posts
    748
    Rep Power
    5

    Default

    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:

    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");
    		}
    		}
    		}
    	}
    FileChatServerDealer:

    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
    			}
    				
    	}
    	
    }
    Client FileSendingSetup:

    Java 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();
    	}
    and the thread for each client

    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()
    }

  9. #9
    al_Marshy_1981 is offline Senior Member
    Join Date
    Feb 2010
    Location
    Waterford, Ireland
    Posts
    748
    Rep Power
    5

    Default

    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)

    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);
    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.

    Any help is appreciated, thanks.

Similar Threads

  1. Replies: 3
    Last Post: 12-10-2009, 04:49 PM
  2. Sending image file over serversocket to browser client
    By maheshsk in forum Advanced Java
    Replies: 1
    Last Post: 12-10-2009, 03:40 PM
  3. Sending image file over serversocket to browser client
    By maheshsk in forum Web Frameworks
    Replies: 1
    Last Post: 12-10-2009, 03:39 PM
  4. Replies: 3
    Last Post: 07-29-2009, 05:52 AM
  5. Replies: 1
    Last Post: 02-10-2009, 10:16 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •