上传图片

来源:互联网 发布:长沙旅游 知乎 编辑:程序博客网 时间:2024/06/05 21:51
/*上传图片的改进版,服务器通过开启多线程,可以服务多个客户端同时上传的文件由主函数的参数传入,在服务器端的图片存储路径由ip决定*/package picDemo2;import java.io.*;import java.net.*;//客户端class Client{public static void main(String[] args) throws Exception{//读入图片并且上传Socket s=new Socket("127.0.0.1",10001);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*10){System.out.println("文件过大");return;}FileInputStream fis=new FileInputStream(file);OutputStream os=s.getOutputStream();byte[] out=new byte[1024];int len=0;while((len=fis.read(out))!=-1){           os.write(out,0,len);}s.shutdownOutput();InputStream is=s.getInputStream();byte[] in=new byte[1024];int num=0;while((num=is.read(in))!=-1){String line=new String(in,0,num);System.out.println(line);}s.close();fis.close();}}//服务器端线程class ServerThread implements Runnable{private Socket s=null;ServerThread(Socket s){this.s=s;}   public void run()   {   try   {int count=1;        InputStream is=s.getInputStream();    String ip=s.getInetAddress().getHostAddress();    File file=new File(ip+"("+count+").jpg");    while(file.exists()) file=new File(ip+"("+(count++)+").jpg");    FileOutputStream fos=new FileOutputStream(file);    byte[] out=new byte[1024];    int len=0;   while((len=is.read(out))!=-1)   {          fos.write(out,0,len);   }    OutputStream os=s.getOutputStream();    os.write("上传成功".getBytes());s.close();fos.close();       }   catch (Exception e)   {   }   }}//服务器端class Server{public static void main(String args[]) throws Exception{ServerSocket ss=new ServerSocket(10001);while(true){Socket s=ss.accept();new Thread(new ServerThread(s)).start();}}}

0 0