How to transfer a JPEG file from client to server using sockets JAVA
I searched on Google about this topic few days back. But I could not found a complete solution.Finally I came up with a solution. These methods from my client and server class shows it.
Client Part
public void uploadFile(File f){
try {
socket=new Socket("127.0.0.1", 4000);
BufferedInputStream in=new BufferedInputStream(new FileInputStream(f));
byte[] buffer = new byte[(int)f.length()];
in.read(buffer, 0, buffer.length);
OutputStream os = socket.getOutputStream();
os.write(buffer, 0, buffer.length);
os.flush();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Server Part
private void stroreFile() {
try {
byte[] mybytearray = new byte[1024];
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream("recieved.jpg");
BufferedOutputStream bos = new BufferedOutputStream(fos);
int bytesRead =0;
while(bytesRead!=-1){
bytesRead = is.read(mybytearray, 0, mybytearray.length);
System.out.println(bytesRead);
if(bytesRead!=-1)
bos.write(mybytearray, 0, bytesRead);
}
bos.close();
fos.close();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
This works for gif and png files on the client side too. But those are saved at the server as JPEG images. But that is not recommended.
Client Part
public void uploadFile(File f){
try {
socket=new Socket("127.0.0.1", 4000);
BufferedInputStream in=new BufferedInputStream(new FileInputStream(f));
byte[] buffer = new byte[(int)f.length()];
in.read(buffer, 0, buffer.length);
OutputStream os = socket.getOutputStream();
os.write(buffer, 0, buffer.length);
os.flush();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Server Part
private void stroreFile() {
try {
byte[] mybytearray = new byte[1024];
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream("recieved.jpg");
BufferedOutputStream bos = new BufferedOutputStream(fos);
int bytesRead =0;
while(bytesRead!=-1){
bytesRead = is.read(mybytearray, 0, mybytearray.length);
System.out.println(bytesRead);
if(bytesRead!=-1)
bos.write(mybytearray, 0, bytesRead);
}
bos.close();
fos.close();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
This works for gif and png files on the client side too. But those are saved at the server as JPEG images. But that is not recommended.
Comments
Post a Comment