Recently, I learned a small project from a certain website. Because I have classes during the day, I wrote them all at night. I completed it today.
The project mainly implements a file uploader, which uploads local files to the server's database (local) through the client login.
First, create two tables as follows:
A file information table
CREATE TABLE `fileinfo` ( `Fname` char(50) NOT NULL, `FInfo` blob NOT NULL, `FId` int(10) NOT NULL AUTO_INCREMENT, PRIMARY KEY (`FId`) ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
A user information table
CREATE TABLE `user` ( `username` char(25) NOT NULL, `password` char(25) NOT NULL, `useid` int(10) NOT NULL AUTO_INCREMENT, PRIMARY KEY (`useid`) ) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8;
User class
package fileUpload; import java.io.Serializable; /* * User entity class*/ public class User implements Serializable{ private static final long serialVersionUID = -7279093338433393181L; private int useid;//User number private String usename;//User name private String usepsd;//User password public User(){ } public User(String usename,String usepsd){ super(); this.usename = usename; this.usepsd = usepsd; } public User(int useid,String usename,String usepsd){ super(); this.useid = useid; this.usename = usename; this.usepsd = usepsd; } public int getUseid() { return useid; } public void setUseid(int useid) { this.useid = useid; } public String getUsename() { return usename; } public void setUsename(String usename) { this.usename = usename; } public String getUsepsd() { return usepsd; } public void setUsepsd(String usepsd) { this.usepsd = usepsd; } }UserService class
package fileUpload; /** * User login and registration operation class*/ import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class UserService { private Connection conn = null; private PreparedStatement ptmt = null; private ResultSet rs = null; // User login public boolean login(User user) { String url = "jdbc:mysql://localhost:3306/fileupload";// Database connection string String sql = "select * from user where username=? and password=?"; try { Class.forName("org.gjt.mm.mysql.Driver").newInstance(); conn = DriverManager.getConnection(url, "root", "1995520"); ptmt = conn.prepareStatement(sql); ptmt.setString(1, user.getUsename()); ptmt.setString(2, user.getUsepsd()); rs = ptmt.executeQuery(); if (rs.next()) { return true; } } catch (Exception e) { e.printStackTrace(); } finally { try { rs.close(); ptmt.close(); } catch (SQLException e) { e.printStackTrace(); } } return false; } //User registration public boolean register(User user){ System.out.println("hello"); String url = "jdbc:mysql://localhost:3306/fileupload";// Database connection string String sql = "insert into user(username,password) values (?,?)"; try { Class.forName("org.gjt.mm.mysql.Driver").newInstance(); conn = DriverManager.getConnection(url, "root", "1995520"); ptmt = conn.prepareStatement(sql); ptmt.setString(1, user.getUsename()); ptmt.setString(2, user.getUsepsd()); ptmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); return false; } finally { try { //rs.close(); ptmt.close(); } catch (SQLException e) { e.printStackTrace(); } } return true; } }FileIofo class
package fileUpload; import java.io.Serializable; /* * File entity class*/ public class FileInfo implements Serializable{ private static final long serialVersionUID = 2554622626228481455L; private int fid;//File number private String fname;//File name private byte[] fcontent;//File content public FileInfo(){ } public FileInfo(String fname,byte[] fcontent){ super(); this.fname = fname; this.fcontent = fcontent; } public FileInfo(int fid,String fname,byte[] fcontent){ super(); this.fid = fid; this.fname = fname; this.fcontent = fcontent; } public int getFid() { return fid; } public void setFid(int fid) { this.fid = fid; } public String getFname() { return fname; } public void setFname(String fname) { this.fname = fname; } public byte[] getFcontent() { return fcontent; } public void setFcontent(byte[] fcontent) { this.fcontent = fcontent; } }FileService class
package fileUpload; /** * File upload operation class*/ import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; public class FileService { private Connection conn = null; private PreparedStatement ptmt = null; //Save the file to the database public boolean save(FileInfo file){ String url = "jdbc:mysql://localhost:3306/fileupload";//Database connection string String sql = "insert into fileinfo(Fname,Finfo) value (?,?)"; try{ Class.forName("org.gjt.mm.mysql.Driver").newInstance(); conn = DriverManager.getConnection(url, "root", "1995520"); ptmt = conn.prepareStatement(sql); ptmt.setString(1, file.getFname()); ptmt.setBytes(2,file.getFcontent()); ptmt.executeUpdate(); }catch(Exception e){ e.printStackTrace(); return false; } finally{ try { ptmt.close(); } catch (SQLException e) { e.printStackTrace(); } } return true; } } package fileUpload;
import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; /* * Start server class*/ public class StartServer { @SuppressWarnings("resource") public static void main(String[] args){ try { // 1. Create a server-side Socket, that is, ServerSocket, specify the bound port, and listen to this port ServerSocket serverSocket = new ServerSocket(8888); Socket socket = null; System.out.println("The server has been started, waiting for the client to connect..."); //Longly listen to wait for the client's connection while (true) { // 2. Call the accept() method to start listening, waiting for the client's connection socket = serverSocket.accept(); //Create a new thread ServerThread serverThread = new ServerThread(socket); //Start the thread serverThread.start(); } } catch (IOException e) { // TODO's automatically generated catch block e.printStackTrace(); } } } } [java] view plain copy View code slices derived from my code slices package fileUpload; import java.io.IOException; /** * Start the client class */ public class StartClient { public static void main(String[] args) throws IOException{ SocketClient client = new SocketClient(); client.showMainMenu();//Show main menu} }package fileUpload;
import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import javax.swing.JOptionPane; /* * Server-side multithreading class*/ public class ServerThread extends Thread { static Socket socket = null; private static ObjectInputStream ois = null;// Object input stream private ObjectOutputStream oos = null;// Object output stream private UserService us = new UserService();// User business object private FileService fs = new FileService();// File business object// Initialize socket public ServerThread(Socket socket) { ServerThread.socket = socket; } public void run() { try { ois = new ObjectInputStream(socket.getInputStream());// Receive messages sent by the client oos = new ObjectOutputStream(socket.getOutputStream());// Used to send messages to the client CommandTransfer transfer = (CommandTransfer) ois.readObject(); // Read the command operation sent by the client to the server transfer = execute(transfer); // Execute the command operation sent by the client to the server oos.writeObject(transfer);// Respond to the client} catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } /* * Execute the command operation sent by the client to the server*/ private CommandTransfer execute(CommandTransfer transfer) { String cmd = transfer.getCmd();// Get the command for the current operation if (cmd.equals("login")) { // User login User user =(User)transfer.getData(); boolean flag = us.login(user); if(flag) JOptionPane.showMessageDialog(null, "Login successfully! "); transfer.setFlag(flag); if(flag){//Judge whether the login is successful transfer.setResult("Login successfully!"); }else{ transfer.setResult("User name or password is incorrect, please log in again!"); } }else if(cmd.equals("register")){//User registration User user = (User) transfer.getData(); us.register(user);//Register user boolean flag = us.register(user); if(flag) JOptionPane.showMessageDialog(null, "Register successfully!"); transfer.setFlag(flag); if(flag){ transfer.setResult("Register successful!"); }else{ transfer.setResult("Register failed!"); } }else if(cmd.equals("uploadFile")){ FileInfo file =(FileInfo)transfer.getData(); fs.save(file); boolean flag = fs.save(file); if(flag) JOptionPane.showMessageDialog(null, "Uploaded successfully!"); transfer.setFlag(flag); if(flag){ transfer.setResult("Uploaded successfully!"); }else{ transfer.setResult("Upload failed!"); } } return transfer; } } package fileUpload; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.net.UnknownHostException; import java.util.Scanner; /** * Main menu class */ public class SocketClient { Scanner input = new Scanner(System.in); private static Socket socket = null;// Client Socket // Main menu public void showMainMenu() throws IOException { System.out.println("****** Welcome to xx file uploader*******"); System.out.println("1.Login/n2.Register/n3.Login"); System.out.println("************************************"); System.out.println("Please select:"); int choice = input.nextInt();// Get user's selection socket = new Socket("localhost", 8888); switch (choice) { case 1: showLogin();// Log in to break; case 2: showRegister();// Register break; case 3: System.out.println("Welcome to support this system"); System.exit(0); default: System.out.println("The input is incorrect! "); System.exit(0); } } // User registration private void showRegister() throws IOException { User user = new User(); CommandTransfer transfer = new CommandTransfer(); int count = 0;// Number of login times while (true) { count++; if (count > 3) { System.out.println("You have failed to log in 3 consecutive times, the program exits!"); System.exit(0); } System.out.print("Please enter the user name: "); user.setUsename(input.next()); System.out.print("Please enter password: "); user.setUsepsd(input.next()); System.out.print("Please enter password again: "); String rePassword = input.next(); if (!user.getUsepsd().equals(rePassword)) { System.out.println("The passwords entered twice are inconsistent!"); System.out.println("*********************"); continue; } transfer.setCmd("register"); transfer.setData(user); try { sendData(transfer);// Send data to the server transfer = getData();// Get the data returned by the server System.out.println(transfer.getResult());// Output display result System.out.println("******************************************"); if (transfer.isFlag()) { break;// If registration is successful, registration will not be repeated} } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { } } showLogin();// Login after registration is successful} // Get server data public static CommandTransfer getData() throws IOException { // TODO Auto-generated method stub ObjectInputStream ois = null; CommandTransfer res = null; try { if(socket.isClosed()) socket = new Socket("localhost", 8888); ois = new ObjectInputStream(socket.getInputStream()); res = (CommandTransfer) ois.readObject(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (ois != null) { try { ois.close(); //socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return res; } /* * Upload file*/ private void showUploadFile() throws IOException { System.out.println("Please enter the absolute path to upload the file:"); String path = input.next(); FileInfo file = null; FileInputStream fis = null; BufferedInputStream bis = null; String fname = path.substring(path.lastIndexOf("/") + 1); try { fis = new FileInputStream(path); byte[] fcontent = new byte[fis.available()]; bis = new BufferedInputStream(fis); bis.read(fcontent); file = new FileInfo(fname, fcontent); } catch (FileNotFoundException e) { e.printStackTrace(); } finally { bis.close(); fis.close(); } CommandTransfer transfer = new CommandTransfer(); transfer.setCmd("uploadFile"); transfer.setData(file); try { sendData(transfer);// Send data to the server transfer = getData();// Get the data returned by the server System.out.println(transfer.getResult());// Output display result} catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { } } // Send data to the server public static void sendData(CommandTransfer cmd) throws IOException { // TODO Auto-generated method stub ObjectOutputStream oos = null; try { if(socket.isClosed())//Judge whether the socket is closed. If closed, open socket = new Socket("localhost", 8888); oos = new ObjectOutputStream(socket.getOutputStream()); oos.writeObject(cmd); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // User logs in to private void showLogin() throws IOException { User user = new User(); CommandTransfer transfer = new CommandTransfer(); while (true) { System.out.print("Please enter the user name: "); user.setUsename(input.next()); System.out.print("Please enter the password: "); user.setUsepsd(input.next()); transfer.setCmd("login"); transfer.setData(user); try { sendData(transfer);// Send data to the server transfer = getData();// Get the data returned by the server System.out.println(transfer.getResult());// Output display result System.out.println("************************************************"); if (transfer.isFlag()) { break;// If the registration is successful, the registration will not be repeated} } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { } } showUploadFile();// Upload the file after login successfully} } }The operation renderings are as follows:
The file has been saved to the database. This project is quite good for friends who want to practice Socket communication and mysql.
The above is the Java Socket+mysql implementation simple file uploader introduced by the editor. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support to Wulin.com website!