使用socket将文件上传到服务器磁盘上
上传原理:客户端使用本地字节输入流读取本地文件,然后使用网络输出流上传文件到服务器端,服务器端使用网络输入流读取客户端上传过来的 文件,服务器端再使用其本地输出流将文件保存到磁盘上,服务端使用网络输出流回写“上传成功”,客户端使用网络输入流接收服务端回写的数据。
/**
* tcp客户端 读取本地文件,上传到远程服务器的硬盘上
*
* @author chencaidao
* @creat 2021-05-07 16:42
*/
public class TcpClient {
/**
* 1.客户端使用本地字节输入流读取本地文件
* 2.客户端使用网络输出流将文件上传到服务器端
* 3.服务器端使用网络输入流读取文件
* 4.服务器端使用本地输出流将文件保存到硬盘上
* 5.服务端使用网络输出流回写“上传成功”,
* 6.客户端使用网络输入流接收服务端的回写的数据
* 7.释放资源
*/
public static void main(String[] args) {
FileInputStream fileInputStream = null;
Socket socket = null;
try {
//1.客户端使用本地字节输入流读取本地文件
fileInputStream = new FileInputStream(new File("D:\\图片\\王秋紫写真4k美女壁纸_彼岸图网.jpg"));
//2.创建Socket 指定服务器ip 和应有的端口号
InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
socket = new Socket(inetAddress, 8999);
//3.客户端使用网络输出流将文件上传到服务器端
OutputStream outputStream = socket.getOutputStream();
//4.将读取到的文件,写到输出流
int len = 0;
byte[] bytes = new byte[1024];
while ((len = fileInputStream.read(bytes)) != -1) {
outputStream.write(bytes,0,len);
}
socket.shutdownOutput();
//5.接收服务器端回写的数据
InputStream inputStream = socket.getInputStream();
int len2 = 0;
byte[] bytes2 = new byte[1024];
while ((len2 = inputStream.read(bytes2)) != -1) {
System.out.println(new String(bytes2,0,len2));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//6.释放资源
if(fileInputStream != null){
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(socket != null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}```
```java
/**
* Tcp服务端,接收客户端上传过来的文件保存到本地硬盘上
*
* @author chencaidao
* @creat 2021-05-07 16:47
*/
public class TcpServer {
/**
* 1.客户端使用本地字节输入流读取本地文件
* 2.客户端使用网络输出流将文件上传到服务器端
* 3.服务器端使用网络输入流读取文件
* 4.服务器端使用本地输出流将文件保存到硬盘上
* 5.服务端使用网络输出流回写“上传成功”,
* 6.客户端使用网络输入流接收服务端的回写的数据
* 7.释放资源
*/
public static void main(String[] args) throws IOException {
//1.创建服务器端socket
ServerSocket serverSocket = new ServerSocket(8999);
while (true){
//2.接收客户端Socket
Socket accept = serverSocket.accept();
new Thread(new Runnable() {
@Override
public void run() {
try {
//3.获取网络输入流,读取客户端上传过来的文件
InputStream inputStream = accept.getInputStream();
//4.创建本地输出流,将读取到的文件保存到硬盘上 d:upload
File file = new File("D:\\upload");
//5.判断文件夹是否存在 不存在则创建
if (!file.exists()){
file.mkdirs();
}
String fileName = System.currentTimeMillis()+Math.random()+".jpg";
FileOutputStream bufferedOutputStream = new FileOutputStream(file.getAbsoluteFile()+"//"+fileName);
//6.网络输入流读取上传过来的文件,本地输出流将文件保存到磁盘上
int len = 0;
byte[] bytes = new byte[1024];
while ((len = inputStream.read(bytes)) != -1) {
bufferedOutputStream.write(bytes,0,len);
}
//7.回写“上传成功”给客户端
OutputStream outputStream = accept.getOutputStream();
outputStream.write("上传成功".getBytes());
bufferedOutputStream.close();
accept.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
}
}