Android實(shí)現(xiàn)頭像上傳功能
之前做這個(gè)頭像上傳功能還是花了好多時(shí)間的,今天我將我的代碼分享給大家先看效果圖

首先看上傳圖片的工具類,一點(diǎn)都沒有少復(fù)制就可以用
**
* Created by Administrator on 2016/7/28.
* 上傳圖片工具類
*/
public class UploadUtil {
private static UploadUtil uploadUtil;
private static final String BOUNDARY = UUID.randomUUID().toString(); // 邊界標(biāo)識(shí) 隨機(jī)生成
private static final String PREFIX = "--";
private static final String LINE_END = "\r\n";
private static final String CONTENT_TYPE = "multipart/form-data"; // 內(nèi)容類型
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; // 讀取超時(shí)
private int connectTimeout = 10 * 1000; // 超時(shí)時(shí)間
/***
* 請(qǐng)求使用多長時(shí)間
*/
private static int requestTime = 0;
private static final String CHARSET = "utf-8"; // 設(shè)置編碼
/***
* 上傳成功
*/
public static final int UPLOAD_SUCCESS_CODE = 1;
/**
* 文件不存在
*/
public static final int UPLOAD_FILE_NOT_EXISTS_CODE = 2;
/**
* 服務(wù)器出錯(cuò)
*/
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上傳文件到服務(wù)器
*
* @param filePath 需要上傳的文件的路徑
* @param fileKey 在網(wǎng)頁上<input type=file name=xxx/> xxx就是這里的fileKey
* @param RequestURL 請(qǐng)求的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上傳文件到服務(wù)器
*
* @param file 需要上傳的文件
* @param fileKey 在網(wǎng)頁上<input type=file name=xxx/> xxx就是這里的fileKey
* @param RequestURL 請(qǐng)求的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, "請(qǐng)求的URL=" + RequestURL);
Log.i(TAG, "請(qǐng)求的fileName=" + file.getName());
Log.i(TAG, "請(qǐng)求的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"); // 請(qǐng)求方式
conn.setRequestProperty("Charset", CHARSET); // 設(shè)置編碼
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");
/**
* 當(dāng)文件不為空,把文件包裝并且上傳
*/
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
StringBuffer sb = null;
String params = "";
/***
* 以下是用于上傳參數(shù)
*/
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();
/**
* 這里重點(diǎn)注意: name里面的值為服務(wù)器端需要key 只有這個(gè)key 才可以得到對(duì)應(yīng)的文件
* 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很重要的 ,用于服務(wù)器端辨別文件的類型的
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());
/**
* 獲取響應(yīng)碼 200=成功 當(dāng)響應(yīng)成功,獲取響應(yīng)的流
*/
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, "上傳結(jié)果:"
+ result);
return;
} else {
Log.e(TAG, "request error" + res);
sendMessage(UPLOAD_SERVER_ERROR_CODE, "上傳失?。篶ode=" + res);
return;
}
} catch (MalformedURLException e) {
sendMessage(UPLOAD_SERVER_ERROR_CODE, "上傳失?。篹rror=" + e.getMessage());
e.printStackTrace();
return;
} catch (IOException e) {
sendMessage(UPLOAD_SERVER_ERROR_CODE, "上傳失敗:error=" + e.getMessage());
e.printStackTrace();
return;
}
}
/**
* 發(fā)送上傳結(jié)果
*
* @param responseCode
* @param responseMessage
*/
private void sendMessage(int responseCode, String responseMessage) {
onUploadProcessListener.onUploadDone(responseCode, responseMessage);
}
/**
* 下面是一個(gè)自定義的回調(diào)函數(shù),用到回調(diào)上傳文件是否完成
*
* @author shimingzheng
*/
public static interface OnUploadProcessListener {
/**
* 上傳響應(yīng)
*
* @param responseCode
* @param message
*/
void onUploadDone(int responseCode, String message);
/**
* 上傳中
*
* @param uploadSize
*/
void onUploadProcess(int uploadSize);
/**
* 準(zhǔn)備上傳
*
* @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;
}
/**
* 獲取上傳使用的時(shí)間
*
* @return
*/
public static int getRequestTime() {
return requestTime;
}
public static interface uploadProcessListener {
}
/**
* 將Bitmap轉(zhuǎn)換成文件
* 保存文件
*
* @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;
}
}
從相冊(cè)獲取圖片的方法
/**
* 從相冊(cè)選擇圖片來源
*/
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);
}
從系統(tǒng)相機(jī)拍照獲取照片
/**
* 從系統(tǒng)相機(jī)選擇圖片來源
*/
private void getCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// 下面這句指定調(diào)用相機(jī)拍照后的照片存儲(chǔ)的路徑
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(
Environment.getExternalStorageDirectory(), "hand.jpg")));
startActivityForResult(intent, CAMERA_REQUEST);
}
調(diào)用系統(tǒng)裁剪工具裁剪圖片
/****
* 調(diào)用系統(tǒng)自帶切圖工具對(duì)圖片進(jìn)行裁剪
* 微信也是
*
* @param uri
*/
private void photoClip(Uri uri) {
// 調(diào)用系統(tǒng)中自帶的圖片剪裁
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, "image/*");
// 下面這個(gè)crop=true是設(shè)置在開啟的Intent中設(shè)置顯示的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);
}
上傳服務(wù)器的方法
/**
* 上傳圖片到服務(wù)器
*/
private void toUploadFile() {
pd = ProgressDialog.show(this, "", "正在上傳文件...");
pd.show();
String fileKey = "avatarFile";
UploadUtil uploadUtil = UploadUtil.getInstance();
uploadUtil.setOnUploadProcessListener(MainActivity.this); //設(shè)置監(jiān)聽器監(jiān)聽上傳狀態(tài)
Map<String, String> params = new HashMap<String, String>();//上傳map對(duì)象
params.put("userId", "");
uploadUtil.uploadFile(filepath, fileKey, "上傳頭像的地址", params);
Toast.makeText(this, "上傳成功", Toast.LENGTH_LONG).show();
}
重新服務(wù)器響應(yīng)方法
/**
* 上傳服務(wù)器響應(yīng)回調(diào)
*/
@Override
public void onUploadDone(int responseCode, String message) {
//上傳完成響應(yīng)
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) {
//準(zhǔn)備上傳
Message msg = Message.obtain();
msg.what = UPLOAD_INIT_PROCESS;
msg.arg1 = fileSize;
}
重寫這些方法需要實(shí)現(xiàn)接口
public class MainActivity extends AppCompatActivity implements View.OnClickListener, UploadUtil.OnUploadProcessListener {
重寫onActivityResult獲取數(shù)據(jù)
@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()) {
//對(duì)相機(jī)拍照照片進(jìn)行裁剪
photoClip(Uri.fromFile(file));
}
}
break;
case PHOTO_REQUEST://從相冊(cè)取
if (data != null) {
Uri uri = data.getData();
//對(duì)相冊(cè)取出照片進(jìn)行裁剪
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與用戶進(jìn)行交互
mImageView.setImageBitmap(photo);
}
}
break;
}
}
源碼下載:Android實(shí)現(xiàn)頭像上傳功能
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Android入門之在子線程中調(diào)用Handler詳解
這篇文章主要為大家詳細(xì)介紹了Android如何在子線程中調(diào)用Handler,文中的示例代碼講解詳細(xì),有需要的朋友可以借鑒參考下,希望能夠?qū)Υ蠹矣兴鶐椭?/div> 2022-12-12
Android實(shí)現(xiàn)側(cè)滑只需一步
這篇文章主要介紹了Android實(shí)現(xiàn)側(cè)滑只需一步,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-03-03
Android系統(tǒng)進(jìn)程間通信(IPC)機(jī)制Binder中的Server啟動(dòng)過程源代碼分析
本文主要介紹Android IPC機(jī)制Binder中的Server啟動(dòng)過程源代碼,這里對(duì)Binder 中Server 啟動(dòng)過程中的源碼做了詳細(xì)的介紹,有研究Android源碼 Binder 通信的小伙伴可以參考下2016-08-08
Android App中的多個(gè)LinearLayout嵌套布局實(shí)例解析
這篇文章主要介紹了Android App中的多個(gè)LinearLayout嵌套布局實(shí)例,利用線性布局來排列按鈕是安卓應(yīng)用布局中的常用做法,需要的朋友可以參考下2016-04-04
淺談RecyclerView(完美替代ListView,GridView)
RecyclerView絕對(duì)是一款功能強(qiáng)大的控件,涵蓋了ListView,GridView,瀑布流等數(shù)據(jù)表現(xiàn)的形式。本文對(duì)其進(jìn)行系統(tǒng)介紹,有需要的朋友可以看下2016-12-12
Android Studio提示inotify大小不足的解決辦法
大家在使用Android Studio導(dǎo)入AOSP源碼的時(shí)候,可能會(huì)遇到inotify大小不足的問題,這篇文章就給大家介紹了怎么解決這個(gè)問題的方法,有需要的朋友們可以參考借鑒。2016-09-09
Android 屬性動(dòng)畫原理與DataBinding
這篇文章主要介紹了Android 屬性動(dòng)畫原理與DataBinding的相關(guān)資料,需要的朋友可以參考下2017-04-04
Android自定義View展示W(wǎng)ifi信號(hào)強(qiáng)弱指示方法示例
這篇文章主要給大家介紹了關(guān)于Android自定義View展示W(wǎng)ifi信號(hào)強(qiáng)弱指示的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),文末給出了完整的實(shí)例供大家參考學(xué)習(xí),需要的朋友可以參考借鑒,下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2017-08-08最新評(píng)論

