Exercise: File upload example

File upload case

File upload analysis diagram

  1. [Client] Input stream, read file data from hard disk to the program.
  2. [Client] Output stream, write file data to the server.
  3. [Server] Input stream, read file data to server program.
  4. [Server] Output stream, write file data to server hard disk.

File Upload

Basic realization

Server implementation:

  1. Create a server ServerSocket object, and the port number to be specified by the system
  2. Use the method accept in the ServerSocket object to obtain the requested client Socket object
  3. Use the getInputStream method in the Socket object to obtain the network byte input stream InputStream object
  4. Determine whether the d:\upload folder exists, and create it if it does not exist
  5. Create a local byte output stream FileOutputStream object, bind the destination to be output in the constructor
  6. Use the read method in the InputStream object of the network byte input stream to read the file uploaded by the client
  7. Use the method write in the local byte output stream FileOutputStream object to save the read file to the hard disk of the server
  8. Use the getOutputStream method in the Socket object to obtain the network byte output stream OutputStream object
  9. Use the method write in the OutputStream object of the network byte output stream to write back "Upload successful" to the client
  10. Release resources (FileOutputStream, Socket, ServerSocket)
package com.itheima.demo02.FileUpload;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;


public class TCPServer {
    
    
    public static void main(String[] args) throws IOException {
    
    

        ServerSocket serverSocket=new ServerSocket(8888);

        Socket socket = serverSocket.accept();

        InputStream socketInputStream = socket.getInputStream();

        File file=new File("d:\\upload");
        if(!file.exists()){
    
    
            file.mkdirs();
        }

        FileOutputStream fos=new FileOutputStream(file+"\\copy.jpg");


        int len=0;
        byte[] bytes=new byte[1024];
        while((len=socketInputStream.read(bytes))!=-1){
    
    
            fos.write(bytes,0,len);
        }


        OutputStream socketOutputStream = socket.getOutputStream();

        socketOutputStream.write("上传成功".getBytes());

        fos.close();
        socket.close();
        serverSocket.close();
    }
}

Client implementation:

  1. Create a local byte input stream FileInputStream object, bind the data source to be read in the constructor
  2. Create a client Socket object and bind the IP address and port number of the server in the construction method
  3. Use the method getOutputStream in Socket to obtain the OutputStream object of the network byte output stream
  4. Use the method read in the FileInputStream object of the local byte input stream to read the local file
  5. Use the method write in the OutputStream object of the network byte output stream to upload the read file to the server
  6. Use the method getInputStream in Socket to obtain the InputStream object of the network byte input stream
  7. Use the method read in the InputStream object of the network byte input stream to read the data written back by the service
  8. Release resources (FileInputStream, Socket)
package com.itheima.demo02.FileUpload;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class TCPClient {
    
    
    public static void main(String[] args) throws IOException {
    
    

        FileInputStream fis=new FileInputStream("C:\\Users\\联想\\Pictures\\Camera Roll\\源.jpg");

        Socket socket=new Socket("127.0.0.1",8888);

        OutputStream socketOutputStream = socket.getOutputStream();

        int len;
        byte[] bytes=new byte[1024];
        while((len=fis.read(bytes))!=-1){
    
    
            socketOutputStream.write(bytes,0,len);
        }

        InputStream socketInputStream = socket.getInputStream();

        while((len=socketInputStream.read(bytes))!=-1){
    
    
            System.out.println(new String(bytes,0,len));
        }

        fis.close();
        socket.close();
    }
}

Before
Source picture
running after running
Transferred picture

File upload optimization analysis

  1. The file name is hard to write

    On the server side, if the name of the saved file is hard-coded, it will eventually cause the server hard disk to retain only one file. It is recommended to use the system time optimization to ensure that the file name is unique

  2. The problem of circular reception

    On the server side, it means to save a file and then close it, and subsequent users can no longer upload it. This is not in line with the reality. Using cyclic improvement, you can continuously receive files from different users. The code is as follows:

  3. Efficiency issues

    On the server side, when receiving large files, it may take a few seconds. At this time, it cannot receive uploads from other users. Therefore, using multi-threading technology to optimize, the code is as follows:

Optimized implementation

package com.itheima.demo02.FileUpload;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;


public class TCPServer {
    
    
    public static void main(String[] args) throws IOException {
    
    

        ServerSocket serverSocket=new ServerSocket(8888);
        while (true){
    
    //使服务器长期运行
            Socket socket = serverSocket.accept();

            new Thread(new Runnable() {
    
    
                @Override
                public void run() {
    
    
                    try {
    
    
                        InputStream socketInputStream = socket.getInputStream();

                        File file=new File("d:\\upload");
                        if(!file.exists()){
    
    
                            file.mkdirs();
                        }
                        String filename="itcast"+System.currentTimeMillis()+new Random().nextInt(999999)+".jpg";

                        FileOutputStream fos=new FileOutputStream(file+"\\"+filename);


                        int len=0;
                        byte[] bytes=new byte[1024];
                        while((len=socketInputStream.read(bytes))!=-1){
    
    
                            fos.write(bytes,0,len);
                        }


                        OutputStream socketOutputStream = socket.getOutputStream();

                        socketOutputStream.write("上传成功".getBytes());

                        fos.close();
                        socket.close();
                    }catch (IOException e){
    
    
                        System.out.println(e);
                    }
                }
            }).start();

        }
    }
}

operation result
operation result
File write back

Guess you like

Origin blog.csdn.net/weixin_45966880/article/details/113924673