欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android实现头像上传功能

程序员文章站 2022-04-30 22:43:38
之前做这个头像上传功能还是花了好多时间的,今天我将我的代码分享给大家先看效果图 首先看上传图片的工具类,一点都没有少复制就可以用 ** * create...

之前做这个头像上传功能还是花了好多时间的,今天我将我的代码分享给大家先看效果图

Android实现头像上传功能

首先看上传图片的工具类,一点都没有少复制就可以用

**
 * created by administrator on 2016/7/28.
 * 上传图片工具类
 */
public class uploadutil {
 private static uploadutil uploadutil;
 private static final string boundary = uuid.randomuuid().tostring(); // 边界标识 随机生成
 private static final string prefix = "--";
 private static final string line_end = "\r\n";
 private static final string content_type = "multipart/form-data"; // 内容类型

 private uploadutil() {

 }

 /**
 * 单例模式获取上传工具类
 *
 * @return
 */
 public static uploadutil getinstance() {
 if (null == uploadutil) {
  uploadutil = new uploadutil();
 }
 return uploadutil;
 }

 private static final string tag = "uploadutil";
 private int readtimeout = 10 * 1000; // 读取超时
 private int connecttimeout = 10 * 1000; // 超时时间
 /***
 * 请求使用多长时间
 */
 private static int requesttime = 0;

 private static final string charset = "utf-8"; // 设置编码

 /***
 * 上传成功
 */
 public static final int upload_success_code = 1;
 /**
 * 文件不存在
 */
 public static final int upload_file_not_exists_code = 2;
 /**
 * 服务器出错
 */
 public static final int upload_server_error_code = 3;
 protected static final int what_to_upload = 1;
 protected static final int what_upload_done = 2;

 /**
 * android上传文件到服务器
 *
 * @param filepath 需要上传的文件的路径
 * @param filekey 在网页上<input type=file name=xxx/> xxx就是这里的filekey
 * @param requesturl 请求的url
 */
 public void uploadfile(string filepath, string filekey, string requesturl,
    map<string, string> param) {
 if (filepath == null) {
  sendmessage(upload_file_not_exists_code, "文件不存在");
  return;
 }
 try {
  file file = new file(filepath);
  uploadfile(file, filekey, requesturl, param);
 } catch (exception e) {
  sendmessage(upload_file_not_exists_code, "文件不存在");
  e.printstacktrace();
  return;
 }
 }

 /**
 * android上传文件到服务器
 *
 * @param file 需要上传的文件
 * @param filekey 在网页上<input type=file name=xxx/> xxx就是这里的filekey
 * @param requesturl 请求的url
 */
 public void uploadfile(final file file, final string filekey,
    final string requesturl, final map<string, string> param) {
 if (file == null || (!file.exists())) {
  sendmessage(upload_file_not_exists_code, "文件不存在");
  return;
 }

 log.i(tag, "请求的url=" + requesturl);
 log.i(tag, "请求的filename=" + file.getname());
 log.i(tag, "请求的filekey=" + filekey);
 new thread(new runnable() { //开启线程上传文件
  @override
  public void run() {
  touploadfile(file, filekey, requesturl, param);
  }
 }).start();

 }

 private void touploadfile(file file, string filekey, string requesturl,
    map<string, string> param) {
 string result = null;
 requesttime = 0;

 long requesttime = system.currenttimemillis();
 long responsetime = 0;

 try {
  url url = new url(requesturl);
  httpurlconnection conn = (httpurlconnection) url.openconnection();
  conn.setreadtimeout(readtimeout);
  conn.setconnecttimeout(connecttimeout);
  conn.setdoinput(true); // 允许输入流
  conn.setdooutput(true); // 允许输出流
  conn.setusecaches(false); // 不允许使用缓存
  conn.setrequestmethod("post"); // 请求方式
  conn.setrequestproperty("charset", charset); // 设置编码
  conn.setrequestproperty("connection", "keep-alive");
  conn.setrequestproperty("user-agent", "mozilla/4.0 (compatible; msie 6.0; windows nt 5.1; sv1)");
  conn.setrequestproperty("content-type", content_type + ";boundary=" + boundary);
// conn.setrequestproperty("content-type", "application/x-www-form-urlencoded");

/**
 * 当文件不为空,把文件包装并且上传
 */
  dataoutputstream dos = new dataoutputstream(conn.getoutputstream());
  stringbuffer sb = null;
  string params = "";

/***
 * 以下是用于上传参数
 */
  if (param != null && param.size() > 0) {
  iterator<string> it = param.keyset().iterator();
  while (it.hasnext()) {
   sb = null;
   sb = new stringbuffer();
   string key = it.next();
   string value = param.get(key);
   sb.append(prefix).append(boundary).append(line_end);
   sb.append("content-disposition: form-data; name=\"").append(key).append("\"").append(line_end).append(line_end);
   sb.append(value).append(line_end);
   params = sb.tostring();
   log.i(tag, key + "=" + params + "##");
   dos.write(params.getbytes());
// dos.flush();
  }
  }

  sb = null;
  params = null;
  sb = new stringbuffer();
/**
 * 这里重点注意: name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
 * filename是文件的名字,包含后缀名的 比如:abc.png
 */
  sb.append(prefix).append(boundary).append(line_end);
  sb.append("content-disposition:form-data; name=\"" + filekey
   + "\"; filename=\"" + file.getname() + "\"" + line_end);
  sb.append("content-type:image/pjpeg" + line_end); // 这里配置的content-type很重要的 ,用于服务器端辨别文件的类型的
  sb.append(line_end);
  params = sb.tostring();
  sb = null;

  log.i(tag, file.getname() + "=" + params + "##");
  dos.write(params.getbytes());
/**上传文件*/
  inputstream is = new fileinputstream(file);
  onuploadprocesslistener.initupload((int) file.length());
  byte[] bytes = new byte[1024];
  int len = 0;
  int curlen = 0;
  while ((len = is.read(bytes)) != -1) {
  curlen += len;
  dos.write(bytes, 0, len);
  onuploadprocesslistener.onuploadprocess(curlen);
  }
  is.close();

  dos.write(line_end.getbytes());
  byte[] end_data = (prefix + boundary + prefix + line_end).getbytes();
  dos.write(end_data);
  dos.flush();
//
// dos.write(tempoutputstream.tobytearray());
/**
 * 获取响应码 200=成功 当响应成功,获取响应的流
 */
  int res = conn.getresponsecode();
  responsetime = system.currenttimemillis();
  this.requesttime = (int) ((responsetime - requesttime) / 1000);
  log.e(tag, "response code:" + res);
  if (res == 200) {
  log.e(tag, "request success");
  inputstream input = conn.getinputstream();
  stringbuffer sb1 = new stringbuffer();
  int ss;
  while ((ss = input.read()) != -1) {
   sb1.append((char) ss);
  }
  string s = sb1.tostring();
  result = s;
  log.e(tag, "result : " + result);
  sendmessage(upload_success_code, "上传结果:"
   + result);
  return;
  } else {
  log.e(tag, "request error" + res);
  sendmessage(upload_server_error_code, "上传失败:code=" + res);
  return;
  }
 } catch (malformedurlexception e) {
  sendmessage(upload_server_error_code, "上传失败:error=" + e.getmessage());
  e.printstacktrace();
  return;
 } catch (ioexception e) {
  sendmessage(upload_server_error_code, "上传失败:error=" + e.getmessage());
  e.printstacktrace();
  return;
 }
 }

 /**
 * 发送上传结果
 *
 * @param responsecode
 * @param responsemessage
 */
 private void sendmessage(int responsecode, string responsemessage) {
 onuploadprocesslistener.onuploaddone(responsecode, responsemessage);
 }

 /**
 * 下面是一个自定义的回调函数,用到回调上传文件是否完成
 *
 * @author shimingzheng
 */
 public static interface onuploadprocesslistener {
 /**
  * 上传响应
  *
  * @param responsecode
  * @param message
  */
 void onuploaddone(int responsecode, string message);

 /**
  * 上传中
  *
  * @param uploadsize
  */
 void onuploadprocess(int uploadsize);

 /**
  * 准备上传
  *
  * @param filesize
  */
 void initupload(int filesize);
 }

 private onuploadprocesslistener onuploadprocesslistener;

 public void setonuploadprocesslistener(
  onuploadprocesslistener onuploadprocesslistener) {
 this.onuploadprocesslistener = onuploadprocesslistener;
 }

 public int getreadtimeout() {
 return readtimeout;
 }

 public void setreadtimeout(int readtimeout) {
 this.readtimeout = readtimeout;
 }

 public int getconnecttimeout() {
 return connecttimeout;
 }

 public void setconnecttimeout(int connecttimeout) {
 this.connecttimeout = connecttimeout;
 }

 /**
 * 获取上传使用的时间
 *
 * @return
 */
 public static int getrequesttime() {
 return requesttime;
 }

 public static interface uploadprocesslistener {

 }

 /**
 * 将bitmap转换成文件
 * 保存文件
 *
 * @param bm
 * @param filename
 * @throws ioexception
 */
 public static file savefile(bitmap bm, string path, string filename) throws ioexception {
 file dirfile = new file(path);
 if (!dirfile.exists()) {
  dirfile.mkdir();
 }
 file mycapturefile = new file(path, filename);
 bufferedoutputstream bos = new bufferedoutputstream(new fileoutputstream(mycapturefile));
 bm.compress(bitmap.compressformat.jpeg, 80, bos);
 bos.flush();
 bos.close();
 return mycapturefile;
 }

}

从相册获取图片的方法

/**
 * 从相册选择图片来源
 */
private void getphoto() {
 intent intent = new intent(intent.action_pick, android.provider.mediastore.images.media.external_content_uri);
 intent.setdataandtype(mediastore.images.media.external_content_uri,
  "image/*");
 startactivityforresult(intent, photo_request);
}

从系统相机拍照获取照片

/**
 * 从系统相机选择图片来源
 */
private void getcamera() {
 intent intent = new intent(mediastore.action_image_capture);

 // 下面这句指定调用相机拍照后的照片存储的路径
 intent.putextra(mediastore.extra_output, uri.fromfile(new file(
  environment.getexternalstoragedirectory(), "hand.jpg")));
 startactivityforresult(intent, camera_request);
}

调用系统裁剪工具裁剪图片

/****
 * 调用系统自带切图工具对图片进行裁剪
 * 微信也是
 *
 * @param uri
 */
private void photoclip(uri uri) {
 // 调用系统中自带的图片剪裁
 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", 150);
 intent.putextra("outputy", 150);
 intent.putextra("return-data", true);
 startactivityforresult(intent, photo_clip);
}

上传服务器的方法

/**
 * 上传图片到服务器
 */
private void touploadfile() {
 pd = progressdialog.show(this, "", "正在上传文件...");
 pd.show();
 string filekey = "avatarfile";
 uploadutil uploadutil = uploadutil.getinstance();
 uploadutil.setonuploadprocesslistener(mainactivity.this); //设置监听器监听上传状态

 map<string, string> params = new hashmap<string, string>();//上传map对象
 params.put("userid", "");
 uploadutil.uploadfile(filepath, filekey, "上传头像的地址", params);
 toast.maketext(this, "上传成功", toast.length_long).show();
}

重新服务器响应方法

/**
 * 上传服务器响应回调
 */
@override
public void onuploaddone(int responsecode, string message) {
 //上传完成响应
 pd.dismiss();
 message msg = message.obtain();
 msg.what = upload_file_done;
 msg.arg1 = responsecode;
 msg.obj = message;
}

@override
public void onuploadprocess(int uploadsize) {
 //上传中
 message msg = message.obtain();
 msg.what = upload_in_process;
 msg.arg1 = uploadsize;
}

@override
public void initupload(int filesize) {
 //准备上传
 message msg = message.obtain();
 msg.what = upload_init_process;
 msg.arg1 = filesize;
}

重写这些方法需要实现接口

public class mainactivity extends appcompatactivity implements view.onclicklistener, uploadutil.onuploadprocesslistener {

重写onactivityresult获取数据

@override
protected void onactivityresult(int requestcode, int resultcode, intent data) {
 super.onactivityresult(requestcode, resultcode, data);
 switch (requestcode) {
 case camera_request:
  switch (resultcode) {
  case -1://-1表示拍照成功
   file file = new file(environment.getexternalstoragedirectory()
    + "/hand.jpg");//保存图片
   if (file.exists()) {
   //对相机拍照照片进行裁剪
   photoclip(uri.fromfile(file));
   }
  }
  break;

 case photo_request://从相册取
  if (data != null) {
  uri uri = data.getdata();
  //对相册取出照片进行裁剪
  photoclip(uri);

  }
  break;
 case photo_clip:
  //完成
  if (data != null) {

  bundle extras = data.getextras();
  if (extras != null) {
   bitmap photo = extras.getparcelable("data");
   try {
   //获得图片路径
   filepath = uploadutil.savefile(photo, environment.getexternalstoragedirectory().tostring(), "hand.jpg");
   //上传照片
   touploadfile();
   } catch (ioexception e) {
   e.printstacktrace();
   }
   //上传完成将照片写入imageview与用户进行交互
   mimageview.setimagebitmap(photo);
  }
  }
  break;
 }
}

源码下载:android实现头像上传功能

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。