[转载]android_Socket网络编程实现手机图片上传到电脑

socket编程机制:客户端与服务端通过socket套接字连接后都会返回一个实例对象,分别保存这个对象,就相当于保存的对方的地址。Socket理解为一个可以连通网络上不同计算机程序之间的管道,把一堆数据从管道的A端扔进去,则会从管道的B端出来。管道的端口由两个因素来唯一确认,即机器的IP地址和程序所使用的端口号。端口号就是程序员指定的一个数字,许多著名的木马程序在网络上扫描不同的端口号就是为了获取一个可以连通的端口从而进行破坏。程序不要使用太小的端口号,它们一般被系统占用了,也不要使用一些常用的端口,一般来说使用1000~5000之内的端口比较好

实现功能:

1.实现手机相册中的单个图片上传到电脑指定路径。(手机相册存在固定位置/sdcard/DCIM/Camera/...)

输入*.jpg,*.jpeg等

2.修改之前上传固定位置的单个图片为输入相册中的多个图片名称,用逗号“,”分隔开,然后上传到电脑,提示用户是否上传成功。

3.因为上传照片很难分清哪个照片需要添加照片描述,后来想使用 ExpandableListView下拉列表让用户选择图片内容类型,选择后自动添加到输入框和图片名称以“:”分开,上传电脑以此描述类型命名为图片 名称,为防止图片重名,前面加上上传时原图片名称,上传同一张图片时才会发生覆盖,不会引起图片丢失,还能直观查看图片内容描述。

4.改善项目功能范围太小的缺陷,添加输入手机内某个文件所在路径,就可获取路径下的所有图片全部上传到电脑。

1.首先搭建好客户端环境,新建android-project ,新建activity

    将手机中的图片发送字节给服务端

2.创建手机界面布局mainactivity.xml

      界面中有textview、EditText、Button、ExpandableListView控件

这里的界面效果:

 

3.MainActivity----socket客户端:接收手机图片信息并处理

完成任务1.在固定路径下(sdcard/./.)查找图片文件,输入图片名称实现上传,

               2.实现输入手机内图片文件的绝对路径,然后点击上传按钮,可将图片上传到电脑指定位置。服务器来接收图片并指定存放位置。

               3.实现选择图片的类型并将其图片复制后重命名,以便用户在电脑分辨图片内容并使用。

               4.ExpandableListView下拉列表的的学习和使用,重写下拉列表适配器,显示自定义样式

               5.截取原图片的名称使其与图片内容类型共同组成上传后的图片名称。例如:a.jpg 图片内容类型为旅游,则重命名的名称为旅游a.jpg

  1. public class UploadPhotoActivity extends Activity {  
  2.     private Socket socket;  
  3.     private String ip = "10.11.204.34";//电脑ip地址,在本地连接的属性下查找本机地址  
  4.     private int port = 4652;//端口号  
  5.     String[] imgStrings;  
  6.     BufferedReader reader;  
  7.     ExpandableListView exp;  
  8.     File file;  
  9.     boolean result = false;  
  10.     @Override  
  11.     protected void onCreate(Bundle savedInstanceState) {  
  12.         super.onCreate(savedInstanceState);  
  13.         setContentView(R.layout.activity_upload_photo);  
  14.         查找组件img 、seriesUpload、filePath、exp。。。。  
  15.         exp.setAdapter(getAdapter());  
  16.         //点击子视图文本触发事件  
  17.         exp.setOnChildClickListener(new OnChildClickListener() {  
  18.             @Override  
  19.             public boolean onChildClick(ExpandableListView parent, View v,  
  20.                     int groupPosition, int childPosition, long id) {  
  21.                 String nowString=img.getText().toString().concat(":"+getAdapter().getChild(groupPosition, childPosition).toString());  
  22.                 img.setText(nowString);  
  23.                 exp.collapseGroup(0);//选择子文本后收缩下拉列表  
  24.                 return false;  
  25.             }  
  26.         });  
  27.         //根据图片名称实现上传  
  28.         mButton.setOnClickListener(new Button.OnClickListener() {  
  29.             @Override  
  30.             public void onClick(View v) {  
  31.                 String strString = img.getText().toString();  
  32.                 imgStrings = new String[] {};  
  33.                 if (strString.trim().length() == 0)  
  34.                     return;  
  35.                 if (strString.contains(",")) {// 多张图片上传  
  36.                     imgStrings = strString.split(",");  
  37.                     for (int i = 0; i < imgStrings.length; i++) {  
  38.                         if(imgStrings[i].contains(":"))  
  39.                             upload(imgStrings[i].split(":")[0],imgStrings[i].split(":")[1]);  
  40.                         else  
  41.                             upload(imgStrings[i], "");  
  42.                         getResult(i+1);  
  43.                     }  
  44.                 } else {//只传一张图片  
  45.                     if(strString.contains(":")){//选择图片描述  
  46.                         upload(strString.split(":")[0],strString.split(":")[1]);  
  47.                     }  
  48.                     else//没有选择图片描述  
  49.                         upload(strString, "");  
  50.                     getResult(1);  
  51.                 }  
  52.                   
  53.             }  
  54.         });  
  55.         //根据文件夹路径上传文件内一系列图片  
  56.         seriesUpload.setOnClickListener(new Button.OnClickListener() {  
  57.             @Override  
  58.             public void onClick(View v) {  
  59.                 String pathString = filePath.getText().toString();  
  60.                 imgStrings = new String[] {};  
  61.                 if (pathString.trim().length() == 0)  
  62.                     return;  
  63.                 String[] paths=listFile(filePath.getText().toString());  
  64.                 if (paths.length==0) {// 文件夹没有图片  
  65.                     Toast.makeText(UploadPhotoActivity.this, "文件夹内没有可传图片文件!",  
  66.                             Toast.LENGTH_SHORT).show();  
  67.                     return;  
  68.                 } else {  
  69.                     for (int j = 0; j < paths.length; j++) {  
  70.                         seriesUpload(paths[j]);  
  71.                         getResult(j);//提示是否已上传成功  
  72.                     }  
  73.                 }  
  74.             }  
  75.         });  
  76.     }  
  77.     //i代表上传的图片索引,返回上传结果  
  78.     private void getResult(int i) {   
  79.         if (file.length() != 0)  
  80.             Toast.makeText(UploadPhotoActivity.this, "上传成功!",  
  81.                     Toast.LENGTH_SHORT).show();  
  82.         else  
  83.             Toast.makeText(UploadPhotoActivity.this, "第"+i+"张上传失败,不存在此文件",  
  84.                     Toast.LENGTH_SHORT).show();  
  85.     }  
  86.     //得到文件夹下的所有图片绝对路径  
  87.          public  String[] listFile(String derect) {  
  88.              File file = new File(derect);  
  89.              File[] f = file.listFiles();  
  90.              String Path[] = new String[f.length];  
  91.              for (int i = 0; i < f.length; i++)  
  92.              {  
  93.                      Path[i] = f[i].getPath();  
  94.                      System.out.println(Path[i]);  
  95.              }  
  96.              return Path;        
  97. }  
  98.   
  99.     // 根据图片名称上传照相机中单个照片  
  100.     private void upload(String path,String scrip) {  
  101.         DataOutputStream dos;  
  102.         FileInputStream fis;  
  103.         try {  
  104.             ///sdcard/DCIM/Camera/照相机拍摄后图片所存路径  
  105.             file = new File("/sdcard/DCIM/Camera/" + path.trim());  
  106.             if (file.length() == 0) {  
  107.                 return;  
  108.             } else {  
  109.                 socket = new Socket(ip, port);  
  110.                 dos = new DataOutputStream(socket.getOutputStream());  
  111.                 fis = new FileInputStream(file);  
  112.                 dos.writeUTF(path.substring(0,path.indexOf("."))+scrip+path.substring(path.indexOf(".")));  
  113.                 dos.flush();  
  114.                 byte[] sendBytes = new byte[1024 * 8];  
  115.                 int length;  
  116.                 while ((length = fis.read(sendBytes, 0, sendBytes.length)) > 0) {  
  117.                     dos.write(sendBytes, 0, length);  
  118.                     dos.flush();// 发送给服务器  
  119.                 }  
  120.                 dos.close();//在发送消息完之后一定关闭,否则服务端无法继续接收信息后处理,手机卡机  
  121.                 /*reader = new BufferedReader(new InputStreamReader( 
  122.                         socket.getInputStream())); 
  123.                 result = Boolean.parseBoolean(reader.readLine().toString()); 
  124.                 System.out.println("上传结果" + result);//运行时总是提示socket关闭,不能接收服务端返回的消息 
  125.                 reader.close();*/  
  126.                 fis.close();  
  127.                 socket.close();  
  128.             }  
  129.         } catch (UnknownHostException e) {  
  130.             e.printStackTrace();  
  131.         } catch (FileNotFoundException e) {  
  132.             e.printStackTrace();  
  133.   
  134.         }catch (SocketTimeoutException e) {  
  135.             e.printStackTrace();  
  136.             Toast.makeText(UploadPhotoActivity.this, "超时,上传失败",  
  137.                     Toast.LENGTH_LONG).show();  
  138.         }catch (IOException e) {  
  139.             e.printStackTrace();  
  140.         }  
  141.     }  
  142.     //根据文件夹路径上传所有的图片到服务器  
  143.     //此dirpath是图片绝对路径  
  144.     private void seriesUpload(String dirpath) {  
  145.         DataOutputStream dos;  
  146.         FileInputStream fis;  
  147.         try {  
  148.             file = new File(dirpath);  
  149.             if (file.length() == 0) {  
  150.                 return;  
  151.             } else {  
  152.                 socket = new Socket(ip, port);  
  153.                 dos = new DataOutputStream(socket.getOutputStream());  
  154.                 fis = new FileInputStream(file);  
  155.                 dos.writeUTF(dirpath.substring(dirpath.lastIndexOf("/")+1));//截取图片名称  
  156.                 dos.flush();  
  157.                 byte[] sendBytes = new byte[1024 * 8];  
  158.                 int length;  
  159.                 while ((length = fis.read(sendBytes, 0, sendBytes.length)) > 0) {  
  160.                     dos.write(sendBytes, 0, length);  
  161.                     dos.flush();// 发送给服务器  
  162.                 }  
  163.                 dos.close();//在发送消息完之后一定关闭,否则服务端无法继续接收信息后处理,手机卡机  
  164.                 fis.close();  
  165.                 socket.close();  
  166.             }  
  167.         } catch (UnknownHostException e) {  
  168.             e.printStackTrace();  
  169.         } catch (FileNotFoundException e) {  
  170.             e.printStackTrace();  
  171.         }catch (SocketTimeoutException e) {  
  172.             e.printStackTrace();  
  173.             Toast.makeText(UploadPhotoActivity.this, "超时,上传失败",  
  174.                     Toast.LENGTH_LONG).show();  
  175.         }catch (IOException e) {  
  176.             e.printStackTrace();  
  177.         }  
  178.     }  
  179.     //下拉列表适配器设置成自己需要的样式  
  180.     private ExpandableListAdapter getAdapter(){  
  181.          final String[] generalsTypes = new String[] { "图片分类"};  
  182.          //子视图显示文字  
  183.          final String[] generals = new String[] { "地方特色风景", "个人生活写照、旅游怀念","地图拍摄","美食", "工作需求图片", "办公环境写实","天气图片","幸福一家人", "好友、同事照片", "汽车","明星写真"};  
  184.         //重写adapter类,创建新适配置  
  185.          ExpandableListAdapter adapter=new ExpandableListAdapter(){  
  186.                 @Override  
  187.                 public boolean areAllItemsEnabled() {return false;}  
  188.                 @Override  
  189.                 public Object getChild(int groupPosition, int childPosition) {  
  190.                     return generals[childPosition];  
  191.                 }  
  192.                 @Override  
  193.                 public long getChildId(int groupPosition, int childPosition) {  
  194.                     return childPosition;  
  195.                 }  
  196.                 @Override  
  197.                 public View getChildView(int groupPosition, int childPosition,  
  198.                         boolean isLastChild, View convertView, ViewGroup parent) {  
  199.                      LinearLayout ll = new LinearLayout(  
  200.                              UploadPhotoActivity.this);  
  201.                         ll.setOrientation(0);  
  202.                         TextView textView = new TextView(UploadPhotoActivity.this);  
  203.                         AbsListView.LayoutParams lp = new AbsListView.LayoutParams(  
  204.                                 ViewGroup.LayoutParams.FILL_PARENT, 64);  
  205.                         textView.setLayoutParams(lp);  
  206.                         textView.setGravity(Gravity.CENTER_VERTICAL);  
  207.                         textView.setPadding(36, 0, 0, 0);  
  208.                         textView.setTextSize(18);  
  209.                         textView.setText(getChild(groupPosition, childPosition)  
  210.                                 .toString());  
  211.                         ll.addView(textView);  
  212.                         return ll;  
  213.                 }  
  214.                 @Override  
  215.                 public int getChildrenCount(int groupPosition) {return generals.length;}  
  216.                 @Override  
  217.                 public Object getGroup(int groupPosition) {return generalsTypes[groupPosition];}  
  218.                 @Override  
  219.                 public int getGroupCount() {return generalsTypes.length;}  
  220.                 @Override  
  221.                 public long getGroupId(int groupPosition) {return groupPosition;}  
  222.                 @Override  
  223.                 public View getGroupView(int groupPosition, boolean isExpanded,  
  224.                         View convertView, ViewGroup parent) {  
  225.                         LinearLayout ll = new LinearLayout( UploadPhotoActivity.this);  
  226.                         ll.setOrientation(0);  
  227.                         TextView textView = new TextView(UploadPhotoActivity.this);  
  228.                         AbsListView.LayoutParams lp = new AbsListView.LayoutParams(  
  229.                                 ViewGroup.LayoutParams.FILL_PARENT, 50);  
  230.                         textView.setLayoutParams(lp);  
  231.                         textView.setGravity(Gravity.CENTER_VERTICAL);  
  232.                         textView.setPadding(80, 5, 0, 0);  
  233.                         textView.setTextSize(20);  
  234.                         textView.setTextColor(Color.BLACK);  
  235.                         textView.setText(getGroup(groupPosition).toString());  
  236.                         ll.addView(textView);  
  237.                         return ll;  
  238.                 }  
  239.                 @Override  
  240.                 public boolean hasStableIds() {  
  241.                     return true;  
  242.                 }  
  243.                 @Override  
  244.                 public boolean isChildSelectable(int groupPosition,  
  245.                         int childPosition) {  
  246.                     return true;  
  247.                 }  
  248.                 @Override。。。。。。一系列要实现的父类的方法  
  249.             };  
  250.             return adapter;  
  251.     }  
  252. }  

 

4.创建服务器端,新建java-project,在main方法中写入服务器接收信息代码

     服务端接收字节写入本地电脑文件内

  1. <span style="font-size:14px;">//服务器  
  2. public class TransFileServer {  
  3.     public static void main(String[] args) {  
  4.         uploadThread t = new uploadThread();  
  5.         t.start();  
  6.     }  
  7. }  
  8. class uploadThread extends Thread {  
  9.     private static final int HOST_PORT = 4652;  
  10.     DataInputStream inputStream;  
  11.     FileOutputStream fos;  
  12.     boolean flag = false;  
  13.     @Override  
  14.     public void run() {  
  15.         Socket skt = null;  
  16.         try {  
  17.             ServerSocket server = new ServerSocket(HOST_PORT);  
  18.             while (true) {  
  19.                 skt = server.accept();  
  20.                 System.out.println("接收到Socket请求");  
  21.                 //接收客户端文件  
  22.                 inputStream = new DataInputStream(skt.getInputStream());  
  23.                 PrintWriter writer = new PrintWriter(skt.getOutputStream());  
  24.                 String trueName = inputStream.readUTF();  
  25.                 fos = new FileOutputStream("D://" + trueName);  
  26.                 byte[] inputByte = new byte[1024 * 8];  
  27.                 int length;  
  28.                 while ((length = inputStream.read(inputByte,0,inputByte.length)) > 0) {  
  29.                     System.out.println("正在接收数据..." + length);  
  30.                     flag = true;  
  31.                     fos.write(inputByte, 0, length);  
  32.                     fos.flush();  
  33.                 }  
  34.                 System.out.println("图片接收完成");  
  35.                 fos.close();  
  36.                 inputStream.close();  
  37.                 // 服务器发送消息  
  38.                 writer.println(flag);// 返回是否接收到图片  
  39.                 writer.flush();  
  40.                 writer.close();  
  41.                 skt.close();  
  42.             }  
  43.         }catch (IOException e) {  
  44.             e.printStackTrace();  
  45.         }  
  46.     }  
  47. }</span>  


5.可选择使用较完善的获取图片列表方法代码段:

  1. public List<STRING> getPictures(final String strPath) {   
  2.           List<STRING> list = new ArrayList<STRING>();            
  3.           File file = new File(strPath);   
  4.           File[] files = file.listFiles();            
  5.           if (files == null) {   
  6.               return null;   
  7.           }               
  8.           for(int i = 0; i < files.length; i++) {   
  9.               final File f = files[i];   
  10.               if(f.isFile()) {   
  11.                   try{   
  12.                       int idx = f.getPath().lastIndexOf(".");   
  13.                       if (idx <= 0) {   
  14.                           continue;   
  15.                       }   
  16.                       String suffix = f.getPath().substring(idx);   
  17.                       if (suffix.toLowerCase().equals(".jpg") ||   
  18.                           suffix.toLowerCase().equals(".jpeg") ||   
  19.                           suffix.toLowerCase().equals(".bmp") ||   
  20.                           suffix.toLowerCase().equals(".png") ||   
  21.                           suffix.toLowerCase().equals(".gif") )   
  22.                       {   
  23.                           list.add(f.getPath());   
  24.                       }   
  25.                   } catch(Exception e) {   
  26.                       e.printStackTrace();   
  27.                   }   
  28.               }   
  29.           }               
  30.           return list;   
  31. }  

6.扩展功能;后期将介绍实现文件检索批量上传图片,用户通过Checkbox复选框选择自己要上传的图片(必须是图片文件才可上传,不是图片给用户提示信息),将这些选中的图片可获取图片名称加入到一个list数组保存起来,然后统一上传。

posted @ 2015-01-04 14:37  chenlinyunyi  阅读(540)  评论(0编辑  收藏  举报