欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java Socket+mysql实现简易文件上传器的代码

程序员文章站 2024-03-11 22:59:01
最近跟着某网站学习了一个小项目,因为白天有课,所以都是晚上写的,今天把它完成了。 项目主要是实现一个文件上传器,通过客户端的登陆,把本地文件上传到服务器的数据库(本地的)...

最近跟着某网站学习了一个小项目,因为白天有课,所以都是晚上写的,今天把它完成了。

项目主要是实现一个文件上传器,通过客户端的登陆,把本地文件上传到服务器的数据库(本地的)。

首先建两个表如下:

一个文件信息表

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();// 登陆成功后进行文件的上传 
} 
}

运行效果图如下:

Java Socket+mysql实现简易文件上传器的代码Java Socket+mysql实现简易文件上传器的代码

文件已保存到数据库中了,这个项目对于想练练socket通信和mysql的朋友来说,还是挺不错的。

以上所述是小编给大家介绍的java socket+mysql实现简易文件上传器,希望对大家有所帮助