您的位置:首页 > 编程语言 > Java开发

java实现图片上传

2013-11-06 21:23 423 查看
/*
*  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 + "上传失败!");
}

}
}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: