点击相册,选中后上传图像
2019-03-22 本文已影响6人
穿越平行宇宙
- 添加权限与依赖
权限
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.CAMERA"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
依赖
//retrofit基本依赖
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'io.reactivex.rxjava2:rxjava:2.0.1' //RxJava
implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
implementation 'com.squareup.okhttp3:okhttp:3.10.0'//okhttp3
implementation 'com.google.code.gson:gson:2.2.4'//gson
implementation 'com.android.support:design:27.1.1' //防止版本错误
implementation 'com.github.bumptech.glide:glide:3.8.0' //解析图片(glide图片加载框架)
implementation 'com.squareup.picasso:picasso:2.3.2' //解析图片
- 在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">
<Button
android:id="@+id/btn1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="拍照" />
<Button
android:id="@+id/btn2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="相册" />
<ImageView
android:id="@+id/img"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
- 需要使用到的实体类
public class UpLoadBean {
/**
* code : 200
* res : 上传文件成功
* data : {"url":"http://yun918.cn/study/public/uploadfiles/123/944365-ee747d1e331ed5a4.png"}
*/
private int code;
private String res;
private DataBean data;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getRes() {
return res;
}
public void setRes(String res) {
this.res = res;
}
public DataBean getData() {
return data;
}
public void setData(DataBean data) {
this.data = data;
}
public static class DataBean {
/**
* url : http://yun918.cn/study/public/uploadfiles/123/944365-ee747d1e331ed5a4.png
*/
private String url;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
}
- 在Activity 中实现效果
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
/**
* 拍照
*/
private Button mBtn1;
/**
* 相册
*/
private Button mBtn2;
private ImageView mImg;
private int ALBUM_CODE = 200;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
mBtn1 = (Button) findViewById(R.id.btn1);
mBtn1.setOnClickListener(this);
mBtn2 = (Button) findViewById(R.id.btn2);
mBtn2.setOnClickListener(this);
mImg = (ImageView) findViewById(R.id.img);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
default:
break;
case R.id.btn1:
break;
case R.id.btn2:
takePICK();
break;
}
}
private void takePICK() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
openAlbum();
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 200);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (requestCode == 200) {
openAlbum();
}
}
}
//打开相册
private void openAlbum() {
//启动相册
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
startActivityForResult(intent, ALBUM_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK){//判断回调成功
if (requestCode == ALBUM_CODE) {//相册
//获取到相册选中后的图片URI路径
Uri imageUri = data.getData();
//显示相册选中后的图片
try {
Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
mImg.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//文件上传,将Uri路径转换为File对象
//处理uri,7.0以后的fileProvider 把URI 以content provider 方式 对外提供的解析方法
/*File file = getFileFromUri(imageUri, this);
if (file.exists()){
uploadFile(file);
}*/
}
}
}
private void uploadFile(File file) {
String url = "http://yun918.cn/study/public/file_upload.php";
OkHttpClient client = new OkHttpClient.Builder()
.build();
RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpg"), mFile);
MultipartBody body = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("key", "fafda")
.addFormDataPart("file", mFile.getName(), requestBody)
.build();
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.d(TAG, "onFailure: " + e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String result = response.body().string();
Gson gson = new Gson();
final UpLoadBean upLoadBean = gson.fromJson(result, UpLoadBean.class);
runOnUiThread(new Runnable() {
@Override
public void run() {
if (upLoadBean != null) {
if (upLoadBean.getCode() == 200) {
Toast.makeText(MainActivity.this, upLoadBean.getRes(), Toast.LENGTH_SHORT).show();
Glide.with(MainActivity.this).load(upLoadBean.getData().getUrl()).into(mImg);
Log.d(TAG, "run: " + upLoadBean.getData().getUrl());
} else {
Toast.makeText(MainActivity.this, upLoadBean.getRes(), Toast.LENGTH_SHORT).show();
}
}
}
});
}
});
}
}