最近跟着某网站学习了一个小项目,因为白天有课,所以都是晚上写的,今天把它完成了。
项目主要是实现一个文件上传器,通过客户端的登陆,把本地文件上传到服务器的数据库(本地的)。
首先建两个表如下:
一个文件信息表
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;
一个用户信息表
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类
package fileUpload; import java.io.Serializable; /* * 用户实体类 */ public class User implements Serializable{ private static final long serialVersionUID = -7279093338433393181L; private int useid;//用户编号 private String usename;//用户名 private String usepsd;//用户密码 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类
package fileUpload; /** * 用户登陆与注册操作类 */ 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; // 用户登录 public boolean login(User user) { String url = "jdbc:mysql://localhost:3306/fileupload";// 数据库连接字符串 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; } //用户注册 public boolean register(User user){ System.out.println("hello"); String url = "jdbc:mysql://localhost:3306/fileupload";// 数据库连接字符串 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类
package fileUpload; import java.io.Serializable; /* * 文件实体类 */ public class FileInfo implements Serializable{ private static final long serialVersionUID = 2554622626228481455L; private int fid;//文件编号 private String fname;//文件名 private byte[] fcontent;//文件内容 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类
package fileUpload; /** * 文件上传操作类 */ 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; //将文件保存到数据库中 public boolean save(FileInfo file){ String url = "jdbc:mysql://localhost:3306/fileupload";//数据库连接字符串 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; /* * 启动服务器类 */ public class StartServer { @SuppressWarnings("resource") public static void main(String[] args){ try { // 1.创建一个服务器端Socket,即ServerSocket,指定绑定的端口,并监听此端口 ServerSocket serverSocket = new ServerSocket(8888); Socket socket = null; System.out.println("服务器已启动,等待客户端的连接..."); //循环监听等待客户端的连接 while (true) { // 2.调用accept()方法开始监听,等待客户端的连接 socket = serverSocket.accept(); //创建一个新的线程 ServerThread serverThread = new ServerThread(socket); //启动线程 serverThread.start(); } } catch (IOException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } } } [java] view plain copy 在CODE上查看代码片派生到我的代码片 package fileUpload; import java.io.IOException; /** * 启动客户端类 */ public class StartClient { public static void main(String[] args) throws IOException{ SocketClient client = new SocketClient(); client.showMainMenu();//显示主菜单 } }
package fileUpload;
import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import javax.swing.JOptionPane; /* * 服务器端多线程处理类 */ public class ServerThread extends Thread { static Socket socket = null; private static ObjectInputStream ois = null;// 对象输入流 private ObjectOutputStream oos = null;// 对象输出流 private UserService us = new UserService();// 用户业务对象 private FileService fs = new FileService();// 文件业务对象 // 通过构造方法,初始化socket public ServerThread(Socket socket) { ServerThread.socket = socket; } public void run() { try { ois = new ObjectInputStream(socket.getInputStream());//接收客户端发来的消息 oos = new ObjectOutputStream(socket.getOutputStream());//用来向客户端发送消息 CommandTransfer transfer = (CommandTransfer) ois.readObject(); // 读取客户端发送到服务器的指令操作 transfer = execute(transfer); // 执行客户端送到服务器的指令操作 oos.writeObject(transfer);// 响应客户端 } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } /* * 执行客户端发送到服务器的指令操作 */ private CommandTransfer execute(CommandTransfer transfer) { String cmd = transfer.getCmd();// 获取当前操作的指令 if (cmd.equals("login")) { // 用户登录 User user =(User)transfer.getData(); boolean flag = us.login(user); if(flag) JOptionPane.showMessageDialog(null, "登陆成功!"); transfer.setFlag(flag); if(flag){//判断登陆是否成功 transfer.setResult("登陆成功!"); }else{ transfer.setResult("用户名或密码不正确,请重新登陆!"); } }else if(cmd.equals("register")){//用户注册 User user = (User) transfer.getData(); us.register(user);//注册用户 boolean flag = us.register(user); if(flag) JOptionPane.showMessageDialog(null, "注册成功!"); transfer.setFlag(flag); if(flag){ transfer.setResult("注册成功!"); }else{ transfer.setResult("注册失败!"); } }else if(cmd.equals("uploadFile")){ FileInfo file =(FileInfo)transfer.getData(); fs.save(file); boolean flag = fs.save(file); if(flag) JOptionPane.showMessageDialog(null, "上传成功!"); transfer.setFlag(flag); if(flag){ transfer.setResult("上传成功!"); }else{ transfer.setResult("上传失败!"); } } 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; /** * 主菜单类 */ public class SocketClient { Scanner input = new Scanner(System.in); private static Socket socket = null;// 客户端Socket // 主菜单 public void showMainMenu() throws IOException { System.out.println("******欢迎使用xx文件上传器******"); System.out.println("1.登录\n2.注册\n3.退出"); System.out.println("****************************"); System.out.println("请选择:"); int choice = input.nextInt();// 获取用户的选择 socket = new Socket("localhost", 8888); switch (choice) { case 1: showLogin();// 登录 break; case 2: showRegister();// 注册 break; case 3: System.out.println("欢迎你对本系统的支持"); System.exit(0); default: System.out.println("输入有误!"); System.exit(0); } } // 用户注册 private void showRegister() throws IOException { User user = new User(); CommandTransfer transfer = new CommandTransfer(); int count = 0;// 登陆次数 while (true) { count++; if (count > 3) { System.out.println("你已连续3次登陆失败,程序退出!"); System.exit(0); } System.out.print("请输入用户名:"); user.setUsename(input.next()); System.out.print("请输入密码:"); user.setUsepsd(input.next()); System.out.print("请再次输入密码:"); String rePassword = input.next(); if (!user.getUsepsd().equals(rePassword)) { System.out.println("两次输入的密码不一致!"); System.out.println("**********************"); continue; } transfer.setCmd("register"); transfer.setData(user); try { sendData(transfer);// 将数据发送到服务器 transfer = getData();// 获取服务器返回的数据 System.out.println(transfer.getResult());// 输出显示结果 System.out.println("*****************************"); if (transfer.isFlag()) { break;// 如果注册成功,则不再重复执行注册 } } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { } } showLogin();// 注册成功后显示登陆 } // 获得服务器的数据 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; } /* * 上传文件 */ private void showUploadFile() throws IOException { System.out.println("请输入上传文件的绝对路径:"); 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);// 将数据发送到服务器 transfer = getData();// 获取服务器返回的数据 System.out.println(transfer.getResult());// 输出显示结果 } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { } } // 向服务器发送数据 public static void sendData(CommandTransfer cmd) throws IOException { // TODO Auto-generated method stub ObjectOutputStream oos = null; try { if(socket.isClosed())//判断socket是否被关闭,如果关闭,就打开 socket = new Socket("localhost", 8888); oos = new ObjectOutputStream(socket.getOutputStream()); oos.writeObject(cmd); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // 用户登陆 private void showLogin() throws IOException { User user = new User(); CommandTransfer transfer = new CommandTransfer(); while (true) { System.out.print("请输入用户名:"); user.setUsename(input.next()); System.out.print("请输入密码:"); user.setUsepsd(input.next()); transfer.setCmd("login"); transfer.setData(user); try { sendData(transfer);// 将数据发送到服务器 transfer = getData();// 获取服务器返回的数据 System.out.println(transfer.getResult());// 输出显示结果 System.out.println("*****************************"); if (transfer.isFlag()) { break;// 如果注册成功,则不再重复执行注册 } } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { } } showUploadFile();// 登陆成功后进行文件的上传 } }
运行效果图如下:
文件已保存到数据库中了,这个项目对于想练练Socket通信和mysql的朋友来说,还是挺不错的。
以上所述是小编给大家介绍的Java Socket+mysql实现简易文件上传器,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!