头像上传
依赖
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
implementation 'io.reactivex.rxjava2:rxandroid:2.1.0'
implementation 'com.facebook.fresco:fresco:1.13.0'
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:id="@+id/iv_photo"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="拍照"
android:id="@+id/photo"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="从相册选"
android:id="@+id/photo_sd"
/>
</LinearLayout>
RetrofitUtils.java网络工具类
package com.uploadapp;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* date:2019/4/29
*/
public class RetrofitUtils {
private String baseUrl = "http://172.17.8.100";
//设置BaseUrl
public RetrofitUtils setBaseUrl(String baseUrl) {
this.baseUrl = baseUrl;
return this;
}
//get请求
public RetrofitUtils get(String url, Map<String, String> map) {
if (map == null) {//如果不需要参数,那么自己去创建一个空的集合
map = new HashMap<>();
}
BaseService service = getBaseService();
Call<ResponseBody> call = service.get(url, map);
doCall(call);
return this;
}
//post请求
public RetrofitUtils post(String url, Map<String, String> map) {
BaseService service = getBaseService();
Call<ResponseBody> call = service.post(url, map);
doCall(call);
return this;
}
//上传
public RetrofitUtils upload(String url, Map<String, String> map, String path) {
MediaType mediaType = MediaType.parse("multipart/form-data; charset=utf-8");
File file=new File(path);
RequestBody body=RequestBody.create(mediaType,file);
MultipartBody.Part part=MultipartBody.Part.createFormData("image",file.getName(),body);
Retrofit retrofit = new Retrofit.Builder().baseUrl(baseUrl).build();
BaseService service = retrofit.create(BaseService.class);
Call<ResponseBody> call = service.uploadPic(url, map, part);
doCall(call);
return this;
}
private void doCall(Call<ResponseBody> call) {
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
if (listener != null) {
listener.success(response.body().string());
}
if (mHttpStreamListener != null) {
mHttpStreamListener.success(response.body().byteStream());
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
if (listener != null) {
listener.fail(t.getMessage());
}
if (mHttpStreamListener != null) {
mHttpStreamListener.fail(t.getMessage());
}
}
});
}
private BaseService getBaseService() {
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(baseUrl).build();
return retrofit.create(BaseService.class);
}
private HttpListener listener;
public void result(HttpListener listener) {
this.listener = listener;
}
public interface HttpListener {
void success(String data);
void fail(String error);
}
private HttpStreamListener mHttpStreamListener;
public void resultStream(HttpStreamListener mHttpStreamListener) {
this.mHttpStreamListener = mHttpStreamListener;
}
public interface HttpStreamListener {
void success(InputStream inputStream);
void fail(String error);
}
}
图片上传代码
BaseService
package com.uploadapp;
import java.util.Map;
import okhttp3.MultipartBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.HeaderMap;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;
import retrofit2.http.QueryMap;
import retrofit2.http.Url;
/**
* date:2019/4/29
*/
public interface BaseService {
@GET
Call<ResponseBody> get(@Url String url, @QueryMap Map<String, String> map);
@POST
Call<ResponseBody> post(@Url String url, @QueryMap Map<String, String> map);
//上传
@Multipart
@POST
Call<ResponseBody> uploadPic(@Url String url,
@HeaderMap Map<String, String> map,
@Part MultipartBody.Part part);
}
MainActivity
package com.uploadapp;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* date:2019/4/29
*/
public class MainActivity extends AppCompatActivity {
private static String path = "/sdcard/myHead/";//sd路径
private ImageView ivPhoto;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ivPhoto = (ImageView) findViewById(R.id.iv_photo);
findViewById(R.id.photo).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//拍照
Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent2.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
"head.jpg")));
startActivityForResult(intent2, 2);//采用ForResult打开
}
});
findViewById(R.id.photo_sd).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//从相册里选
Intent intent1 = new Intent(Intent.ACTION_PICK, null);
intent1.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
startActivityForResult(intent1, 1);
}
});
}
/**
* 调用系统的裁剪
*
* @param uri
*/
public void cropPhoto(Uri uri) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, "image/*");
intent.putExtra("crop", "true");
// aspectX aspectY 是宽高的比例
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
// outputX outputY 是裁剪图片宽高
intent.putExtra("outputX", 127);
intent.putExtra("outputY", 127);
intent.putExtra("scale", true);
intent.putExtra("noFaceDetection", false);//不启用人脸识别
intent.putExtra("return-data", true);
startActivityForResult(intent, 3);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 1:
if (resultCode == RESULT_OK) {
cropPhoto(data.getData());//裁剪图片
}
break;
case 2:
if (resultCode == RESULT_OK) {
File temp = new File(Environment.getExternalStorageDirectory()
+ "/head.jpg");
cropPhoto(Uri.fromFile(temp));//裁剪图片
}
break;
case 3:
if (data != null) {
Bundle extras = data.getExtras();
if (extras == null) {
return;
}
Bitmap head = extras.getParcelable("data");
if (head != null) {
ivPhoto.setImageBitmap(head);
/**
* 上传服务器代码
*/
String fileName = path + "/head.jpg";//图片名字
upLoad(fileName);//上传到服务器
// setPicToView(head);//保存在SD卡中
}
}
break;
}
}
//上传
private String upUrl = "/small/user/verify/v1/modifyHeadPic";//上传
private void upLoad(String sdPath) {
Map<String, String> headMap = new HashMap<>();
headMap.put("userId", "2325");
headMap.put("sessionId", "15565177104002325");
new RetrofitUtils().upload(upUrl, headMap, sdPath).result(new RetrofitUtils.HttpListener() {
@Override
public void success(String data) {
Toast.makeText(MainActivity.this, data, Toast.LENGTH_LONG).show();
}
@Override
public void fail(String error) {
Toast.makeText(MainActivity.this, error, Toast.LENGTH_LONG).show();
}
});
}
//保存到SD卡
private void setPicToView(Bitmap mBitmap) {
String sdStatus = Environment.getExternalStorageState();
if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
return;
}
FileOutputStream b = null;
File file = new File(path);
file.mkdirs();// 创建文件夹
String fileName = path + "/head.jpg";//图片名字
try {
b = new FileOutputStream(fileName);
mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
//关闭流
b.flush();
b.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
不要忘记加上联网权限以及读写权限,这里就不写了