android 图片上传,使用 httpclient 的MultipartEntity 上传

该上传案例使用springmvc 为后台使用httpclient 方法传递文件比文件流和base64方法上传文件更方便简介。

该案例首先获取图片并将图片写入应用的SD卡文件夹。然后再上传给服务器

关于在SD卡中创建应用文件夹请参照

http://blog.csdn.net/u012373815/article/details/47614715

准备工作导入JAR包

Android 端需要导入

apache-mime4j-0.6.jar

httpmime-4.2.jar

Springmvc 需要导入

commons-fileupload-1.2.2.jar

commons-io-2.4.jar

所需jar包我以上传到我的资源页

http://download.csdn.net/detail/u012373815/9001465

Android 端需要添加访问网络权限和SD卡读写权限。

<!-- 网络权限 -->

<uses-permission android:name="android.permission.INTERNET"/>

   <!--sd卡权限 -->

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

 <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>        

  

1.  上传图片首先需要获取图片

OnClickListenerzhuceimg 为某一个控件的点击方法,点击选取图片

  // 提取图片

public classOnClickListenerzhuceimg implements OnClickListener {

     @Override

     public void onClick(View v) {

       ShowPickDialog();

     }

  }

 

  /*

   * 提示对话框

   */

  private void ShowPickDialog() {

     new AlertDialog.Builder(this)

         .setTitle("设置头像")

         .setNegativeButton("相册",

 new DialogInterface.OnClickListener() {

  public void onClick(DialogInterfacedialog, intwhich) {

dialog.dismiss();// 对话框消失

if (SdCardUtil.checkSdCard() == true) {

Intent intent = new Intent(Intent.ACTION_PICK);

       intent.setType("image/*");// 相片类型

       startActivityForResult(intent,1); // 跳到onActivityResult case1

} else {

  Toast.makeText(Userzhuce.this, "SD卡不存在",  Toast.LENGTH_LONG).show();}

            }

         })

         .setPositiveButton("拍照", newDialogInterface.OnClickListener() {

  public void onClick(DialogInterfacedialog, intwhichButton) {

              dialog.dismiss();

              // 调用拍照

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

// 下面这句指定调用相机拍照后的照片存储的路径文件名用电话代替          intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri

     .fromFile(new File(Environment

.getExternalStorageDirectory(),userphone + ".jpg")));

  startActivityForResult(intent,2); // 跳到onActivityResult case2

            }

         }).show();

  }

 

  @Override

protected voidonActivityResult(intrequestCode, intresultCode, Intent data) {

     switch (requestCode) {

     // 如果是直接从相册获取

     case 1:

       startPhotoZoom(data.getData());

       break;

     // 如果是调用相机拍照时

     case 2:

       Filetemp = newFile(Environment.getExternalStorageDirectory()

            +"/"+ userphone+ ".jpg");

       startPhotoZoom(Uri.fromFile(temp));

       break;

     // 取得裁剪后的图片

     case 3:

       /*

        * 非空判断大家一定要验证,如果不验证的话, * 在剪裁之后如果发现不满意,要重新裁剪,丢弃

        * 当前功能时,会报NullException

        */

       if (data != null) {

         setPicToView(data); //保存图片到SD        } else{

Toast.makeText(this, "没拿到数据", 1).show();

       }break;

     default:break;

     }

super.onActivityResult(requestCode, resultCode, data);

  }

 

  // 裁剪图片方法实现

  public void startPhotoZoom(Uri uri){

     Intentintent = newIntent("com.android.camera.action.CROP");

     intent.setDataAndType(uri,"image/*");

// 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪

     intent.putExtra("crop", "true");

     // aspectX aspectY 是宽高的比例

     intent.putExtra("aspectX",1);

     intent.putExtra("aspectY",1);

     // outputX outputY 是裁剪图片宽高

     intent.putExtra("outputX",500);

     intent.putExtra("outputY",500);

     intent.putExtra("return-data",true);

     startActivityForResult(intent,3); // 跳到onActivityResult case3

  }

  /*

   * 保存裁剪之后的图片数据 *

   */

  private void setPicToView(Intentpicdata) {

     Bundleextras = picdata.getExtras();

     Bitmapphoto = null;

     if (extras != null) {

     photo= (Bitmap) extras.get("data");

Drawable drawable = new BitmapDrawable(photo);

// 转换为drawable 用于显示

       zhuceimg.setImageDrawable(drawable);

     }

     if (photo != null) {

       saveImgTosdFile(photo);

     }

  }

  // 将图片写到sd

  public void saveImgTosdFile(Bitmapbitmap) {

     FileOutputStreamfos = null;

     Stringfilename = SdCardUtil.getSdPath() + SdCardUtil.FILEDIR + "/"

         +SdCardUtil.FILEPHOTO+ "/"+ System.currentTimeMillis();

     if (!filename.isEmpty()) {

       imageurl = filename;

     }

     try {

       fos= newFileOutputStream(filename);

       //将图片写道SD卡中以filename为名字bitmap.compress(Bitmap.CompressFormat.PNG,

60, fos);

     }catch(FileNotFoundException e) {

       // TODO Auto-generated catch block

       e.printStackTrace();

     }finally{

       try {

            fos.flush();        

       }catch(IOException e) {

         // TODO Auto-generated catch block

         e.printStackTrace();

       }

     }

  }

  // end 图片

 

  // 上传和返回结果处理

final Handler handlerzhuce= newHandler() {

     public void handleMessage(Messagemsg) { 

       Stringstr = (String) msg.obj;

       if (!str.equals("no")) {

Toast.makeText(Userzhuce.this, "完善信息成功!", Toast.LENGTH_SHORT).show();

startActivity(new Intent(Userzhuce.this, Wo.class));

       }else{

Toast.makeText(Userzhuce.this, "信息完善失败!!", Toast.LENGTH_SHORT)

              .show();

       }

     }

  };

  // 点击更新

 

public classOnClickListenerzhuce implements OnClickListener {

       @Override

     public void onClick(View v) {

       // TODO Auto-generated method stub

       if (zhucenc.getText().toString().equals("")) {

         Toast.makeText(Userzhuce.this, "昵称不能为空!!!", Toast.LENGTH_SHORT)

              .show();

       }else{

     //imageurl  为图片在手机上存储的位置

     Filefile = newFile(imageurl);

newThread(updateUser.updateuser(

HttpPath.USERUPDATE_PATH,userphone,

zhucenc.getText().toString(),

zhuceaddress.getText().toString(),

handlerzhuce, file)).start();

       }

     }

  }

2.  上传图片的httpclient 工具类

 import java.io.File;

import java.io.IOException;

import java.io.UnsupportedEncodingException;

import java.nio.charset.Charset;

import org.apache.http.HttpResponse;

import org.apache.http.client.ClientProtocolException;

import org.apache.http.client.HttpClient;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.impl.client.DefaultHttpClient;

import org.apache.http.util.EntityUtils;

import org.apache.http.entity.mime.MultipartEntity;

import org.apache.http.entity.mime.content.FileBody;

import org.apache.http.entity.mime.content.StringBody;

import android.os.Handler;

import android.os.Message;

import android.util.Log;

 

public classupdateUser {

public staticRunnable  updateuser (final String path, final String userphone,  final String username,

final String address,  final Handler handler,

final File imgfile  ){

      Runnablerun=newRunnable() {

        Stringresult=null;

        @Override

        public void run() {

           // TODO Auto-generated method stub

   HttpClienthttpClient=newDefaultHttpClient();

           HttpPosthttpPost=newHttpPost(path);

           FileBodyfile=newFileBody(imgfile);

           MultipartEntity emEntity=new MultipartEntity();

        try {//封装所需数据,包括文件和所需的Strig 数据

              emEntity.addPart("file",file);

              emEntity.addPart("userphone",newStringBody(userphone,Charset.forName("utf-8")));

              emEntity.addPart("username",newStringBody(username,Charset.forName("utf-8")));

              emEntity.addPart("address",newStringBody(address,Charset.forName("utf-8")));

              httpPost.setEntity(emEntity);

              Log.i("TAG", "post总字节数:"+emEntity.getContentLength());

              HttpResponsehttpResponse=httpClient.execute(httpPost);

              intcode=httpResponse.getStatusLine().getStatusCode();

              if(code==200)

              {

                 System.out.println("链接成功");   result=EntityUtils.toString(httpResponse.getEntity());                                              

              }

             

              Messagemessage=handler.obtainMessage();

              message.obj=result;

              handler.sendMessage(message);

             

           }catch(UnsupportedEncodingException e) {

              // TODO Auto-generated catch block

              e.printStackTrace();

           }catch(ClientProtocolException e) {

              // TODO Auto-generated catch block

              e.printStackTrace();

           }catch(IOException e) {

              // TODO Auto-generated catch block

              e.printStackTrace();

           }                    

        }

      };

      return run;

   }

3.  服务器端controller 代码书写

关于service 的代码书写就不在这里写了

//@RequestParam("file")为文件上传的标识 “file“

 @RequestMapping("/upUser")

   @ResponseBody

   public StringupUser(HttpServletRequest httpRequest, @RequestParam("file") MultipartFile file) throws Exception {

      System.out.println("sdfsdfsdf");

      Stringuserphone = httpRequest.getParameter("userphone");

      Stringusername = httpRequest.getParameter("username");

      Stringaddress = httpRequest.getParameter("address");

      System.out.println(userphone+username+"______");

      // 接收图片

      //图片存储路径

      Stringimagepath = httpRequest.getSession().getServletContext()

           .getRealPath("/")

           +"images"+ "/"+ userphone + ".jpg";

        Filef = newFile(imagepath);

        file.transferTo(f);

      //图片名称

String  userimg="/backtow/images"

+"/"+userphone+".jpg";

      Usersuser=newUsers();

      user.setUserphone(userphone);

      user.setUsername(username);

      user.setAddress(address);

      user.setUserimg(userimg);

      Stringresult=userservice.upUser(user);

      return result;

   }

你可能感兴趣的:(android,springMVC,图片上传)