一、FileUpload
- 实现步骤:
*1、创建一个本地字节收入流 FileInputStream 对象,构造方法中绑定读取的数据源
*2、创建一个socket对象,构造方法中绑定 服务器的IP地址和端口号
*3、使用socket中的方法getoutputStream 获取网络字节输出流
*4、使用本地字节输入流 中的read方法,读取本地文件
*5、使用网络输出流中的write方法,把读取到的文件上传到服务器
*6、使用socket中方法,获取输入流对象
*7、通过网络输入流对象中的read方法,读取回写数据
*8、释放资源
客户端
在这里插入代码片public class Client {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("E:\\eclipse\\1.jpg");
Socket socket = new Socket("127.0.0.1",8888);
OutputStream os = socket.getOutputStream();
int len =0;
byte[] bytes= new byte[1024];
while((len=fis.read(bytes))!=-1) {
os.write(bytes,0,len);
}
socket.shutdownOutput();
InputStream is=socket.getInputStream();
while((len= is.read(bytes))!=-1) {
System.out.println(new String(bytes,0,len));
}
fis.close();
socket.close();
}
}
服务器
public class TcpServer {
public static void main(String[] args) throws IOException {
ServerSocket server= new ServerSocket(8888);
Socket socket = server.accept();
InputStream is=socket.getInputStream();
File file=new File("E:\\20210601");
if(!file.exists()) {
file.mkdirs();
}
FileOutputStream fos= new FileOutputStream(file+"1.jpg");
int len=0;
byte[] bytes=new byte[1024];
while((len=is.read(bytes))!=-1) {
fos.write(bytes,0,len);
}
socket.getOutputStream().write("图片上传成功".getBytes());
fos.close();
socket.close();
server.close();
}
}
更改版
服务器
public class TcpServer {
public static void main(String[] args) {
ServerSocket server= new ServerSocket(8888);
while(true) {
Socket socket = server.accept();
new Thread (new Runnable() {
public void run() {
InputStream is=socket.getInputStream();
File file=new File("E:\\20210601");
if(!file.exists()) {
file.mkdirs();
}
String fileName="classFive"+System.currentTimeMillis()+new Random().nextInt(99999)+".jpq";
FileOutputStream fos= new FileOutputStream(file+"2.jpg");
int len=0;
byte[] bytes=new byte[1024];
while((len=is.read(bytes))!=-1) {
fos.write(bytes,0,len);
}
socket.getOutputStream().write("图片上传成功".getBytes());
fos.close();
socket.close();
try {
}catch(IOException e) {
System.out.println(e);
}
}
}
}
客户端
public class Client {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("E:\\eclipse\\1.jpg");
Socket socket = new Socket("127.0.0.1",8888);
OutputStream os = socket.getOutputStream();
int len =0;
byte[] bytes= new byte[1024];
while((len=fis.read(bytes))!=-1) {
os.write(bytes,0,len);
}
socket.shutdownOutput();
InputStream is=socket.getInputStream();
while((len= is.read(bytes))!=-1) {
System.out.println(new String(bytes,0,len));
}
fis.close();
socket.close();
}
}