转自:http://blog.csdn.net/Lvmodel/article/details/9090519?locationNum=13&fps=1
这里实现的效果是:用户在客户端首先点击按钮进行选择图片,当图片选中之后,就会显示在ImageView中,并且在此时将图片上传至服务器。
这里并没有对图片和数据库进行相关联,如果愿意,可以在数据库中建立相应的字段,将图片的存放地址保存即可。
当然在AndroidManifest.xml中的权限还要加上,这里不再赘述。
首先先定义activity_main.xml
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:paddingBottom="@dimen/activity_vertical_margin"
- android:paddingLeft="@dimen/activity_horizontal_margin"
- android:paddingRight="@dimen/activity_horizontal_margin"
- android:paddingTop="@dimen/activity_vertical_margin"
- tools:context=".MainActivity" >
- <Button
- android:id="@+id/ShowImg"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="@string/ShowImg" />
- <ImageView
- android:id="@+id/Img"
- android:layout_below="@id/ShowImg"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"/>
- </RelativeLayout>
接着进行客户端代码的编写:这里要进行的操作就是先选择图片然后再进行上传
MainActivity.Java
- package com.demo.imgshowpro;
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.IOException;
- import android.app.Activity;
- import android.content.ContentResolver;
- import android.content.Intent;
- import android.database.Cursor;
- import android.net.Uri;
- import android.os.Bundle;
- import android.provider.MediaStore;
- import android.view.Menu;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.ImageView;
- public class MainActivity extends Activity {
- private Button showImg = null;
- private ImageView img = null;
- private static final String IMG_TYPE = "image/*";
- private static final int IMG_CODE = 0;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- showImg = (Button) findViewById(R.id.ShowImg);
- img = (ImageView) findViewById(R.id.Img);
- showImg.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
- intent.setType(IMG_TYPE);
- startActivityForResult(intent, IMG_CODE);
- }
- });
- }
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- // Inflate the menu; this adds items to the action bar if it is present.
- getMenuInflater().inflate(R.menu.main, menu);
- return true;
- }
- @Override
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- // RESULT_OK为系统定义的常量
- if(resultCode != RESULT_OK) {
- return;
- }
- ContentResolver resolver = getContentResolver();
- if (resultCode == RESULT_OK) {
- // 获取图片uri
- Uri uri = data.getData();
- try {
- // 显示到bitmap图片
- MediaStore.Images.Media.getBitmap(resolver, uri);
- // 获取图片的路径
- String[] proj = new String[]{MediaStore.Images.Media.DATA};
- Cursor cursor = managedQuery(uri, proj, null, null, null);
- int index = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
- cursor.moveToFirst();
- // 根据索引值获取图片路径
- String path = cursor.getString(index);
- // ImageView里面打印图片
- img.setImageURI(uri);
- // 图片上传服务器
- File file =new File(path);
- Upload upload = new Upload();
- upload.uploadFile(file);
- // 输出本文件存在的位置
- System.out.println(path);
- } catch (FileNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- }
上文中使用的上传图片的类Upload如下:
- package com.demo.imgshowpro;
- import java.io.DataInputStream;
- import java.io.DataOutputStream;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.IOException;
- import java.net.Socket;
- import java.net.UnknownHostException;
- import android.annotation.SuppressLint;
- import android.os.Build;
- import android.os.StrictMode;
- @SuppressLint("NewApi")
- public class Upload {
- // 这里的地址为HOME
- private static final String HOME = "192.168.X.XXX";
- private static final String BUFF = "--";
- Socket socket = null;
- DataOutputStream output = null;
- DataInputStream input = null;
- public void uploadFile(File file) {
- // 如果本系统为4.0以上(Build.VERSION_CODES.ICE_CREAM_SANDWICH为android4.0)
- if (Build.VERSION.SDK_INT > Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
- // 详见StrictMode文档
- StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
- .detectDiskReads().detectDiskWrites().detectNetwork()
- .penaltyLog().build());
- StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
- .detectLeakedSqlLiteObjects().detectLeakedClosableObjects()
- .penaltyLog().penaltyDeath().build());
- }
- try {
- // 连接服务器
- socket = new Socket(HOME, 8888);
- // 得到输出流
- output = new DataOutputStream(socket.getOutputStream());
- // 得到如入流
- input = new DataInputStream(socket.getInputStream());
- /* 取得文件的FileInputStream */
- FileInputStream fStream = new FileInputStream(file);
- String[] fileEnd = file.getName().split("\\.");
- output.writeUTF(BUFF + fileEnd[fileEnd.length - 1].toString());
- System.out.println("buffer------------------" + BUFF
- + fileEnd[fileEnd.length - 1].toString());
- //设置每次写入102400bytes
- int bufferSize = 102400;
- byte[] buffer = new byte[bufferSize];
- int length = 0;
- // 从文件读取数据至缓冲区(值为-1说明已经读完)
- while ((length = fStream.read(buffer)) != -1) {
- /* 将资料写入DataOutputStream中 */
- output.write(buffer, 0, length);
- }
- // 一定要加上这句,否则收不到来自服务器端的消息返回
- socket.shutdownOutput();
- /* close streams */
- fStream.close();
- output.flush();
- /* 取得input内容 */
- String msg = input.readUTF();
- System.out.println("上传成功 文件位置为:" + msg);
- } catch (UnknownHostException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
至此,客户端的代码已经编写完毕,下来为SERVER端的代码:
SocketServer.java
- /**
- *
- */
- package com.demo.server;
- import java.io.BufferedOutputStream;
- import java.io.DataInputStream;
- import java.io.DataOutputStream;
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.net.ServerSocket;
- import java.net.Socket;
- import java.util.Date;
- /**
- * @author 段
- *
- */
- public class SocketServer {
- private static final String BUFF = "--";
- // 存放图片文件夹
- private final static String IMG_RECORD = "D:\\img_record";
- // socket端口
- private final static int PORT = 8888;
- /**
- * @param args
- */
- public static void main(String[] args) {
- // ServerSocket的引用
- ServerSocket ss = null;
- // socket的引用
- Socket socket = null;
- DataInputStream input = null;
- DataOutputStream output = null;
- try {
- // 监听到8888端口
- ss = new ServerSocket(PORT);
- System.out.println("已监听到" + PORT + "端口");
- System.out.println(new Date().toString() + " \n 服务器已经启动...");
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- while (true) {
- try {
- // 等待客户端连接 访问ServerSocket实例的accept方法取得一个客户端Socket对象
- socket = ss.accept();
- if (socket == null || socket.isClosed())
- continue;
- // 得到输入流
- input = new DataInputStream(socket.getInputStream());
- // 得到输出流
- output = new DataOutputStream(socket.getOutputStream());
- // 上传数据
- String pathString = SocketUpLoad(input);
- output.writeUTF(pathString);
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } finally {
- try {
- // 关闭输出流
- if (output != null) {
- output.close();
- }
- // 关闭输入流
- if (input != null) {
- input.close();
- }
- // 关闭Socket连接
- if (socket != null) {
- socket.close();
- }
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- }
- /**
- * 上传
- *
- * @param input
- */
- private static String SocketUpLoad(DataInputStream input) {
- String fileName = null;
- try {
- DataInputStream inputStream = input;
- // 读一个字符串
- String msg = inputStream.readUTF();
- String[] strings = msg.split(BUFF);
- System.out.println(strings[strings.length - 1]);
- // 文件名
- fileName = System.currentTimeMillis() + "."
- + strings[strings.length - 1];
- System.out.println(new Date().toString() + "\t 文件名为:" + fileName);
- // 创建目录
- CreateDir(IMG_RECORD);
- // 将数据读写到文件中
- BufferedOutputStream bo = new BufferedOutputStream(
- new FileOutputStream(new File(
- (IMG_RECORD + "\\" + fileName))));
- int bytesRead = 0;
- byte[] buffer = new byte[102400];
- while ((bytesRead = inputStream.read(buffer, 0, buffer.length)) != -1) {
- bo.write(buffer, 0, bytesRead);
- }
- // 关闭
- bo.flush();
- bo.close();
- System.out.println(new Date().toString() + "\t 数据接收完毕");
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return IMG_RECORD + "\\" + fileName;
- }
- /**
- * 创建目录(不存在则创建)
- * @param dir
- * @return
- */
- public static File CreateDir(String dir) {
- File file = new File(dir);
- if (!file.exists()) {
- file.mkdirs();
- }
- return file;
- }
- }
当选择图片之后,服务端的图片可在D:\img_record文件夹下查找。