简体   繁体   中英

Sending image from client to server

Im new to JAVA so go easy on em please.

I have a server and a client that can successfully connect to each other and other stuff but 1 function of the client is to send an image to the server.Can anybody provide the code for that(in java,not a web app).

Welcome to Java !

To accomplish your task at hand, you can use Sockets.

Client code :

function sendFile (String serverIp, int serverPort) {
    int i;
    FileInputStream fis = new FileInputStream ("/path/to/your/image.jpg");

    Socket sock = new Socket(serverIp, serverPort);
    DataOutputStream os = new DataOutputStream(sock.getOutputStream());
    while ((i = fis.read()) > -1)
        os.write(i);

    fis.close();
    os.close();
    sock.close();
}

Server code :

function listenForFile(int port) {
    ServerSocket socket = new ServerSocket(serverPort);
        while (true) {

            Socket clientSocket = socket.accept();

            DataInputStream dis = new DataInputStream(clientSocket.getInputStream());
            FileOutputStream fout = new FileOutputStream("/path/to/store/image.jpg");
            int i;
            while ( (i = dis.read()) > -1) {
                fout.write(i);
            }

            fout.flush();
            fout.close();
            dis.close();
            clientSocket.close();
        }
}

Note that server method listenForFile() must be called before you call sendFile() on client. And, serverPort must be same on both sides.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM