java用户图片上传_java实现图片上传

/*

* java multiple upload demo

* @author:luowen

* @time:2013-11-06

* */

import java.io.*;

import java.net.*;

class UploadClient

{

public static void main(String[] args)throws Exception

{

if(args.length != 1)

{

System.out.println("输入错误,请正确输入");

return;

}

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

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

{

System.out.println("你输入的不是存在,或者不是文件");

return ;

}

if(!file.getName().endsWith(".jpg"))

{

System.out.println("你输入的文件格式不正确,请输入.jpg格式的文件");

return ;

}

if(file.length() >= 1024*1024*5)

{

System.out.println("你输入的文件过大,请输入小于5M的文件");

return ;

}

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

FileInputStream fos = new FileInputStream(file);

OutputStream os = s.getOutputStream();

byte[] by = new byte[1024];

int len;

while((len = fos.read(by)) != -1)

{

os.write(by,0,len);

}

s.shutdownOutput();

InputStream is = s.getInputStream();

byte[] by1 = new byte[1024];

int num;

while((num = is.read(by)) != -1)

System.out.println(new String(by,0,num));

fos.close();

s.close();

}

}

class UploadServer

{

public static void main(String[] args)

{

try

{

ServerSocket ss = new ServerSocket(10000);

while(true)

{

Socket s = ss.accept();

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

}

}

catch(Exception e)

{

throw new RuntimeException("监听端口失败!");

}

}

}

class UploadThread implements Runnable

{

private Socket s;

UploadThread(Socket s)

{

this.s = s;

}

public void run()

{

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

try

{

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

int count = 0;

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

while(file.exists())

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

FileOutputStream fos = new FileOutputStream(file);

InputStream is = s.getInputStream();

byte[] by = new byte[1024];

int len ;

while((len = is.read(by)) != -1)

{

fos.write(by,0,len);

}

PrintWriter pw = new PrintWriter(s.getOutputStream(),true);

pw.println(ip + "上传成功!");

s.close();

fos.close();

}

catch(Exception e)

{

throw new RuntimeException(ip + "上传失败!");

}

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值