android选择图片并使用socket上传图片

转自:http://blog.csdn.net/Lvmodel/article/details/9090519?locationNum=13&fps=1

这里实现的效果是:用户在客户端首先点击按钮进行选择图片,当图片选中之后,就会显示在ImageView中,并且在此时将图片上传至服务器。

这里并没有对图片和数据库进行相关联,如果愿意,可以在数据库中建立相应的字段,将图片的存放地址保存即可。

当然在AndroidManifest.xml中的权限还要加上,这里不再赘述。

首先先定义activity_main.xml

[html]  view plain  copy
  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:paddingBottom="@dimen/activity_vertical_margin"  
  6.     android:paddingLeft="@dimen/activity_horizontal_margin"  
  7.     android:paddingRight="@dimen/activity_horizontal_margin"  
  8.     android:paddingTop="@dimen/activity_vertical_margin"  
  9.     tools:context=".MainActivity" >  
  10.   
  11.     <Button  
  12.         android:id="@+id/ShowImg"  
  13.         android:layout_width="wrap_content"  
  14.         android:layout_height="wrap_content"  
  15.         android:text="@string/ShowImg" />  
  16.       
  17.     <ImageView   
  18.         android:id="@+id/Img"  
  19.         android:layout_below="@id/ShowImg"  
  20.         android:layout_width="wrap_content"  
  21.         android:layout_height="wrap_content"/>  
  22.   
  23. </RelativeLayout>  

接着进行客户端代码的编写:这里要进行的操作就是先选择图片然后再进行上传

MainActivity.Java

[java]  view plain  copy
  1. package com.demo.imgshowpro;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileNotFoundException;  
  5. import java.io.IOException;  
  6.   
  7. import android.app.Activity;  
  8. import android.content.ContentResolver;  
  9. import android.content.Intent;  
  10. import android.database.Cursor;  
  11. import android.net.Uri;  
  12. import android.os.Bundle;  
  13. import android.provider.MediaStore;  
  14. import android.view.Menu;  
  15. import android.view.View;  
  16. import android.view.View.OnClickListener;  
  17. import android.widget.Button;  
  18. import android.widget.ImageView;  
  19.   
  20. public class MainActivity extends Activity {  
  21.       
  22.     private Button showImg = null;  
  23.     private ImageView img = null;  
  24.     private static final String IMG_TYPE = "image/*";  
  25.     private static final int IMG_CODE = 0;  
  26.   
  27.     @Override  
  28.     protected void onCreate(Bundle savedInstanceState) {  
  29.         super.onCreate(savedInstanceState);  
  30.         setContentView(R.layout.activity_main);  
  31.           
  32.         showImg = (Button) findViewById(R.id.ShowImg);  
  33.           
  34.         img = (ImageView) findViewById(R.id.Img);  
  35.         showImg.setOnClickListener(new OnClickListener() {  
  36.               
  37.             @Override  
  38.             public void onClick(View v) {  
  39.                 Intent intent = new Intent(Intent.ACTION_GET_CONTENT);  
  40.                 intent.setType(IMG_TYPE);  
  41.                 startActivityForResult(intent, IMG_CODE);  
  42.                   
  43.             }  
  44.         });  
  45.     }  
  46.   
  47.     @Override  
  48.     public boolean onCreateOptionsMenu(Menu menu) {  
  49.         // Inflate the menu; this adds items to the action bar if it is present.  
  50.         getMenuInflater().inflate(R.menu.main, menu);  
  51.         return true;  
  52.     }  
  53.   
  54.     @Override  
  55.     protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
  56.   
  57.         // RESULT_OK为系统定义的常量  
  58.         if(resultCode != RESULT_OK) {  
  59.             return;  
  60.         }  
  61.         ContentResolver resolver = getContentResolver();  
  62.           
  63.         if (resultCode == RESULT_OK) {  
  64.             // 获取图片uri  
  65.             Uri uri = data.getData();  
  66.             try {  
  67.                 // 显示到bitmap图片  
  68.                 MediaStore.Images.Media.getBitmap(resolver, uri);  
  69.                 // 获取图片的路径  
  70.                 String[] proj = new String[]{MediaStore.Images.Media.DATA};  
  71.                 Cursor cursor = managedQuery(uri, proj, nullnullnull);  
  72.                   
  73.                 int index = cursor.getColumnIndex(MediaStore.Images.Media.DATA);  
  74.                 cursor.moveToFirst();  
  75.                 // 根据索引值获取图片路径  
  76.                 String path = cursor.getString(index);  
  77.                 // ImageView里面打印图片  
  78.                 img.setImageURI(uri);  
  79.                   
  80.                 // 图片上传服务器  
  81.                 File file =new File(path);  
  82.                 Upload upload = new Upload();  
  83.                 upload.uploadFile(file);  
  84.   
  85.                 // 输出本文件存在的位置  
  86.                 System.out.println(path);  
  87.             } catch (FileNotFoundException e) {  
  88.                 // TODO Auto-generated catch block  
  89.                 e.printStackTrace();  
  90.             } catch (IOException e) {  
  91.                 // TODO Auto-generated catch block  
  92.                 e.printStackTrace();  
  93.             }  
  94.         }  
  95.     }  
  96.       
  97.       
  98.       
  99. }  

上文中使用的上传图片的类Upload如下:

[java]  view plain  copy
  1. package com.demo.imgshowpro;  
  2.   
  3. import java.io.DataInputStream;  
  4. import java.io.DataOutputStream;  
  5. import java.io.File;  
  6. import java.io.FileInputStream;  
  7. import java.io.IOException;  
  8. import java.net.Socket;  
  9. import java.net.UnknownHostException;  
  10.   
  11. import android.annotation.SuppressLint;  
  12. import android.os.Build;  
  13. import android.os.StrictMode;  
  14.   
  15. @SuppressLint("NewApi")  
  16. public class Upload {  
  17.         // 这里的地址为HOME  
  18.     private static final String HOME = "192.168.X.XXX";  
  19.       
  20.     private static final String BUFF = "--";  
  21.   
  22.     Socket socket = null;  
  23.     DataOutputStream output = null;  
  24.     DataInputStream input = null;  
  25.   
  26.     public void uploadFile(File file) {  
  27.   
  28.         // 如果本系统为4.0以上(Build.VERSION_CODES.ICE_CREAM_SANDWICH为android4.0)  
  29.         if (Build.VERSION.SDK_INT > Build.VERSION_CODES.ICE_CREAM_SANDWICH) {  
  30.             // 详见StrictMode文档  
  31.             StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()  
  32.                     .detectDiskReads().detectDiskWrites().detectNetwork()  
  33.                     .penaltyLog().build());  
  34.             StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()  
  35.                     .detectLeakedSqlLiteObjects().detectLeakedClosableObjects()  
  36.                     .penaltyLog().penaltyDeath().build());  
  37.         }  
  38.   
  39.   
  40.         try {  
  41.             // 连接服务器  
  42.             socket = new Socket(HOME, 8888);  
  43.             // 得到输出流  
  44.             output = new DataOutputStream(socket.getOutputStream());  
  45.             // 得到如入流  
  46.             input = new DataInputStream(socket.getInputStream());  
  47.   
  48.             /* 取得文件的FileInputStream */  
  49.             FileInputStream fStream = new FileInputStream(file);  
  50.   
  51.             String[] fileEnd = file.getName().split("\\.");  
  52.             output.writeUTF(BUFF + fileEnd[fileEnd.length - 1].toString());  
  53.             System.out.println("buffer------------------" + BUFF  
  54.                     + fileEnd[fileEnd.length - 1].toString());  
  55.   
  56.             //设置每次写入102400bytes   
  57.             int bufferSize = 102400;  
  58.             byte[] buffer = new byte[bufferSize];  
  59.             int length = 0;  
  60.             // 从文件读取数据至缓冲区(值为-1说明已经读完)  
  61.             while ((length = fStream.read(buffer)) != -1) {  
  62.                 /* 将资料写入DataOutputStream中 */  
  63.                 output.write(buffer, 0, length);  
  64.             }  
  65.             // 一定要加上这句,否则收不到来自服务器端的消息返回  
  66.             socket.shutdownOutput();  
  67.               
  68.             /* close streams */  
  69.             fStream.close();  
  70.             output.flush();  
  71.   
  72.             /* 取得input内容 */  
  73.             String msg = input.readUTF();  
  74.             System.out.println("上传成功  文件位置为:" + msg);  
  75.   
  76.         } catch (UnknownHostException e) {  
  77.             // TODO Auto-generated catch block  
  78.             e.printStackTrace();  
  79.         } catch (IOException e) {  
  80.             // TODO Auto-generated catch block  
  81.             e.printStackTrace();  
  82.         }  
  83.   
  84.     }  
  85.   
  86. }  

至此,客户端的代码已经编写完毕,下来为SERVER端的代码:

SocketServer.java

[java]  view plain  copy
  1. /** 
  2.  *  
  3.  */  
  4. package com.demo.server;  
  5.   
  6. import java.io.BufferedOutputStream;  
  7. import java.io.DataInputStream;  
  8. import java.io.DataOutputStream;  
  9. import java.io.File;  
  10. import java.io.FileOutputStream;  
  11. import java.io.IOException;  
  12. import java.net.ServerSocket;  
  13. import java.net.Socket;  
  14. import java.util.Date;  
  15.   
  16. /** 
  17.  * @author 段 
  18.  *  
  19.  */  
  20. public class SocketServer {  
  21.   
  22.     private static final String BUFF = "--";  
  23.   
  24.     // 存放图片文件夹  
  25.     private final static String IMG_RECORD = "D:\\img_record";  
  26.   
  27.     // socket端口  
  28.     private final static int PORT = 8888;  
  29.   
  30.     /** 
  31.      * @param args 
  32.      */  
  33.     public static void main(String[] args) {  
  34.         // ServerSocket的引用  
  35.         ServerSocket ss = null;  
  36.         // socket的引用  
  37.         Socket socket = null;  
  38.         DataInputStream input = null;  
  39.         DataOutputStream output = null;  
  40.         try {  
  41.             // 监听到8888端口  
  42.             ss = new ServerSocket(PORT);  
  43.             System.out.println("已监听到" + PORT + "端口");  
  44.             System.out.println(new Date().toString() + " \n 服务器已经启动...");  
  45.         } catch (IOException e) {  
  46.             // TODO Auto-generated catch block  
  47.             e.printStackTrace();  
  48.         }  
  49.         while (true) {  
  50.             try {  
  51.                 // 等待客户端连接 访问ServerSocket实例的accept方法取得一个客户端Socket对象  
  52.                 socket = ss.accept();  
  53.                 if (socket == null || socket.isClosed())  
  54.                     continue;  
  55.                 // 得到输入流  
  56.                 input = new DataInputStream(socket.getInputStream());  
  57.                 // 得到输出流  
  58.                 output = new DataOutputStream(socket.getOutputStream());  
  59.                 // 上传数据  
  60.                 String pathString = SocketUpLoad(input);  
  61.   
  62.                 output.writeUTF(pathString);  
  63.   
  64.             } catch (IOException e) {  
  65.                 // TODO Auto-generated catch block  
  66.                 e.printStackTrace();  
  67.             } finally {  
  68.                 try {  
  69.                     // 关闭输出流  
  70.                     if (output != null) {  
  71.                         output.close();  
  72.                     }  
  73.                     // 关闭输入流  
  74.                     if (input != null) {  
  75.                         input.close();  
  76.                     }  
  77.                     // 关闭Socket连接  
  78.                     if (socket != null) {  
  79.                         socket.close();  
  80.                     }  
  81.                 } catch (IOException e) {  
  82.                     // TODO Auto-generated catch block  
  83.                     e.printStackTrace();  
  84.                 }  
  85.             }  
  86.         }  
  87.   
  88.     }  
  89.   
  90.     /** 
  91.      * 上传 
  92.      *  
  93.      * @param input 
  94.      */  
  95.     private static String SocketUpLoad(DataInputStream input) {  
  96.         String fileName = null;  
  97.         try {  
  98.             DataInputStream inputStream = input;  
  99.             // 读一个字符串  
  100.             String msg = inputStream.readUTF();  
  101.   
  102.             String[] strings = msg.split(BUFF);  
  103.             System.out.println(strings[strings.length - 1]);  
  104.   
  105.             // 文件名  
  106.             fileName = System.currentTimeMillis() + "."  
  107.                     + strings[strings.length - 1];  
  108.             System.out.println(new Date().toString() + "\t 文件名为:" + fileName);  
  109.             // 创建目录  
  110.             CreateDir(IMG_RECORD);  
  111.   
  112.             // 将数据读写到文件中  
  113.             BufferedOutputStream bo = new BufferedOutputStream(  
  114.                     new FileOutputStream(new File(  
  115.                             (IMG_RECORD + "\\" + fileName))));  
  116.   
  117.             int bytesRead = 0;  
  118.             byte[] buffer = new byte[102400];  
  119.             while ((bytesRead = inputStream.read(buffer, 0, buffer.length)) != -1) {  
  120.                 bo.write(buffer, 0, bytesRead);  
  121.             }  
  122.             // 关闭  
  123.             bo.flush();  
  124.             bo.close();  
  125.             System.out.println(new Date().toString() + "\t 数据接收完毕");  
  126.   
  127.         } catch (IOException e) {  
  128.             // TODO Auto-generated catch block  
  129.             e.printStackTrace();  
  130.         }  
  131.         return IMG_RECORD + "\\" + fileName;  
  132.     }  
  133.   
  134.     /** 
  135.      *  创建目录(不存在则创建) 
  136.      * @param dir 
  137.      * @return 
  138.      */  
  139.     public static File CreateDir(String dir) {  
  140.         File file = new File(dir);  
  141.         if (!file.exists()) {  
  142.             file.mkdirs();  
  143.         }  
  144.         return file;  
  145.     }  
  146.   
  147. }  

当选择图片之后,服务端的图片可在D:\img_record文件夹下查找。


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值