引用转载http://www.cnblogs.com/eyu8874521/archive/2012/07/20/2600697.html
效果:
客服端代码:
package com.cn.lxz.zhaopian; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import lxz.utils.android.graphics.GraphicsBitmapUtils; import lxz.utils.android.net.UploadFile; import lxz.utils.android.resource.AndroidClass; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.provider.MediaStore; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; public class Activity_UploadPic extends Activity implements Handler.Callback { /** Called when the activity is first created. */ ImageView view_pic; Button view_btn; EditText view_et; // 线程通知上传成功 final Handler upLoadhand = new Handler(this); String[] arrayString = { "拍照", "相册" }; String title = "上传照片"; // 上传的地址 String uploadUrl = "http://192.168.1.101:8080/UploadServlet/UploadServlet?"; String filename = "照片"; private static final int PHOTO_REQUEST_TAKEPHOTO = 1;// 拍照 private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择 private static final int PHOTO_REQUEST_CUT = 3;// 结果 @Override public boolean handleMessage(Message msg) { if (msg.obj != null) { Drawable drawable = new BitmapDrawable((Bitmap) msg.obj); view_pic.setBackgroundDrawable(drawable); Toast.makeText(this, "获得图片并且头像上传成功", 3).show(); }else { Toast.makeText(this, "获得图片,但是头像上传失败,请注意配置uploadUrl上传地址", 3).show(); } return false; } // 创建一个以当前时间为名称的文件 File tempFile = new File(Environment.getExternalStorageDirectory(), getPhotoFileName()); // 对话框 OnClickListener onDialogClick = new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case 0: startCamearPicCut(dialog);// 开启照相 break; case 1: startImageCaptrue(dialog);// 开启图库 break; default: break; } } private void startCamearPicCut(DialogInterface dialog) { // TODO Auto-generated method stub dialog.dismiss(); // 调用系统的拍照功能 Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra("camerasensortype", 2);// 调用前置摄像头 intent.putExtra("autofocus", true);// 自动对焦 intent.putExtra("fullScreen", false);// 全屏 intent.putExtra("showActionIcons", false); // 指定调用相机拍照后照片的储存路径 intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile)); startActivityForResult(intent, PHOTO_REQUEST_TAKEPHOTO); } private void startImageCaptrue(DialogInterface dialog) { // TODO Auto-generated method stub dialog.dismiss(); Intent intent = new Intent(Intent.ACTION_PICK, null); intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*"); startActivityForResult(intent, PHOTO_REQUEST_GALLERY); } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); init(); } private void init() { // TODO Auto-generated method stub view_pic = (ImageView) findViewById(R.id.iv); view_btn = (Button) findViewById(R.id.btn); view_et = (EditText) findViewById(R.id.et); view_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub AlertDialog.Builder dialog = AndroidClass.getListDialogBuilder( Activity_UploadPic.this, arrayString, title, onDialogClick); dialog.show(); } }); } // 使用系统当前日期加以调整作为照片的名称 private String getPhotoFileName() { Date date = new Date(System.currentTimeMillis()); SimpleDateFormat dateFormat = new SimpleDateFormat( "'IMG'_yyyyMMdd_HHmmss"); return dateFormat.format(date) + ".jpg"; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case PHOTO_REQUEST_TAKEPHOTO: startPhotoZoom(Uri.fromFile(tempFile), 150); break; case PHOTO_REQUEST_GALLERY: if (data != null) { startPhotoZoom(data.getData(), 150); } break; case PHOTO_REQUEST_CUT: if (data != null) { setPicToView(data); } break; } super.onActivityResult(requestCode, resultCode, data); } private void startPhotoZoom(Uri uri, int size) { Intent intent = new Intent("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", size); intent.putExtra("outputY", size); intent.putExtra("return-data", true); startActivityForResult(intent, PHOTO_REQUEST_CUT); } // 将进行剪裁后的图片显示到UI界面上 private void setPicToView(Intent picdata) { Bundle bundle = picdata.getExtras(); if (bundle != null) { final Bitmap photo = bundle.getParcelable("data"); new Thread() { @Override public void run() { byte[] photodata = GraphicsBitmapUtils.Bitmap2Bytes(photo); UploadFile uploadFile = new UploadFile(uploadUrl); Map parameters = new HashMap(); parameters.put("msg", view_et.getText().toString()); boolean isUploadSuccess = false; try { isUploadSuccess = uploadFile.defaultUploadMethod( photodata, filename, parameters); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (isUploadSuccess) { upLoadhand.obtainMessage(0, photo).sendToTarget(); } else { upLoadhand.obtainMessage(-1, null).sendToTarget(); } } }.start(); } } }
服务器端
package com.project3gabs.action; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.net.URLEncoder; import java.util.List; import javax.servlet.ServletException; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileItemFactory; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; public class UploadServlet extends HttpServlet { protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("服务器发现上传文件"); System.out.println(this.getServletContext().getRealPath("/")); request.setCharacterEncoding("UTF-8"); if(request.getHeader("user-agent")!=null&&(request.getHeader("user-agent").toLowerCase().indexOf("mozilla")!=-1)) { System.out.println("访问端-PC"); }else { System.out.println("访问端-手机"); } try { request.setCharacterEncoding("UTF-8"); // 设置处理请求参数的编码格式 response.setContentType("text/html;charset=UTF-8"); // 设置Content-Type字段值 PrintWriter out = response.getWriter(); System.out.println("附加信息"+URLEncoder.encode(request.getParameter("msg"),"UTF-8")); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { // 下面的代码开始使用Commons-UploadFile组件处理上传的文件数据 FileItemFactory factory = new DiskFileItemFactory(); // 建立FileItemFactory对象 ServletFileUpload upload = new ServletFileUpload(factory); // 分析请求,并得到上传文件的FileItem对象 List<FileItem> items = upload.parseRequest(request); // 从web.xml文件中的参数中得到上传文件的路径 String uploadPath = this.getServletContext().getRealPath("/")+"\\upload\\"; File file = new File(uploadPath); if (!file.exists()) { file.mkdir(); } String filename = null; // 上传文件保存到服务器的文件名 InputStream is = null; // 当前上传文件的InputStream对象 // 循环处理上传文件 for (FileItem item : items) { // 处理普通的表单域 if (item.isFormField()) { try { System.out.println(item.getFieldName()+item.getString()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } if (item.getFieldName().equals("filename")) { // 如果新文件不为空,将其保存在filename中 if (!item.getString().equals("")) filename = item.getString("UTF-8"); System.out.println("filename="+filename); } } // 处理上传文件 else if (item.getName() != null && !item.getName().equals("")) { // 从客户端发送过来的上传文件路径中截取文件名 filename = item.getName().substring( item.getName().lastIndexOf("\\") + 1); is = item.getInputStream(); // 得到上传文件的InputStream对象 } } // 将路径和上传文件名组合成完整的服务端路径 filename = uploadPath + filename; System.out.println("filename="+filename); // 如果服务器已经存在和上传文件同名的文件,则输出提示信息 if (new File(filename).exists()) { new File(filename).delete(); } // 开始上传文件 if (!filename.equals("")) { // 用FileOutputStream打开服务端的上传文件 FileOutputStream fos = new FileOutputStream(filename); byte[] buffer = new byte[8192]; // 每次读8K字节 int count = 0; // 开始读取上传文件的字节,并将其输出到服务端的上传文件输出流中 while ((count = is.read(buffer)) > 0) { fos.write(buffer, 0, count); // 向服务端文件写入字节流 } fos.close(); // 关闭FileOutputStream对象 is.close(); // InputStream对象 System.out.println("文件上传成功!"); } } catch (Exception e) { } } }
本文:Demo代码下载