服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|

服务器之家 - 编程语言 - JAVA教程 - Java Socket+mysql实现简易文件上传器的代码

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

2020-06-27 13:15PettyKoKo JAVA教程

最近在做一个小项目,项目主要需求是实现一个文件上传器,通过客户端的登陆,把本地文件上传到服务器的数据库(本地的)。下面通过本文给大家分享下实现代码,感兴趣的朋友一起看看吧

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

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

首先建两个表如下:

一个文件信息表

?
1
2
3
4
5
6
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;

一个用户信息表

?
1
2
3
4
5
6
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类

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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类

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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类

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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类

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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;

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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;

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
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实现简易文件上传器,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!

原文链接:http://blog.csdn.net/qq_31028891/article/details/52928045

延伸 · 阅读

精彩推荐