input浏览服务器端文件,java服务器端用传输给客户端文件流(fileinputstream)

package cn.hncu.tcp.upload;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.OutputStream;

import java.net.Socket;

import java.net.UnknownHostException;

public class UploadPicClient {

public static void main(String[] args) {

if(args.length!=1){

System.out.println("请指定文件");

return;

}

File file=new File(args[0]);

if(!(file.exists() && file.isFile())){

System.out.println("上传的文件不存在");

}

if(!(file.getName().endsWith(".jpg")|| file.getName().endsWith(".gif"))){

System.out.println("文件格式有误");

return;

}

if(file.length()>=1024*1024*2){

System.out.println("文件过大");

return;

}

//上传

try {

Socket s=new Socket("127.0.0.1",10008);

FileInputStream fin=new FileInputStream(file);

OutputStream out=s.getOutputStream();

byte[] buf=new byte[1024];

while((fin.read(buf))!=-1){

out.write(buf, 0, buf.length);

}

s.shutdownOutput();//解决阻塞问题

byte[] b=new byte[1024];

s.getInputStream().read(b);

System.out.println(new String(b));

s.close();

} catch (UnknownHostException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}

}

//服务器端

[java] view plain copy

package cn.hncu.tcp.upload;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.net.ServerSocket;

import java.net.Socket;

public class UploadPicServer {

public static void main(String[] args) {

try {

ServerSocket server=new ServerSocket(10008);

while(true){//多线程实现多用户并发访问

Socket s=server.accept();

new Thread(new UploadThread(s)).start();

}

} catch (IOException e) {

e.printStackTrace();

}

}

}

class UploadThread implements Runnable{

private Socket s;

public UploadThread(Socket s) {

this.s=s;

}

@Override

public void run() {

try {

String ip=s.getInetAddress().getHostAddress();

System.out.println(ip+"connected....");

InputStream in=s.getInputStream();

File dir=new File("f:\\mypic");

if(!dir.exists()){

dir.mkdir();

}

//下面这段主要是把同一个Ip地址的客户端发来的照片用127.0.0.1.jpg格式和127.0.0.1(1)区分开来。

int count=0;

File file=new File(dir,ip+".jpg");

while(file.exists()){//第二次如果存在,则在后面加(1)(2)等。

file=new File(dir,ip+"("+(count++)+")"+".jpg");

}

//从客户端读取

FileOutputStream fout=new FileOutputStream(file);

byte[] buf=new byte[1024];

int len=in.read(buf);

while((len=in.read(buf))!=-1){

fout.write(buf, 0, len);

}

//给客户端上传成功的提示

OutputStream out=s.getOutputStream();

out.write("上传成功".getBytes());

fout.close();

s.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值