1、打开相册
@OnClick(R.id.But_losing)
public void click() {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_PICK);
intent.setType("image/*");
this.startActivityForResult(intent, 1);
}
2、接收
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
Uri uri = data.getData();//图片url
System.out.println("url:" + uri);
ContentResolver resolver = getContentResolver();
Cursor query = resolver.query(uri, null, null, null, null);
boolean first = query.moveToFirst();
if (first) {
try {
//获取图片地址
int columnIndex = query.getColumnIndex("_data");
String path = query.getString(columnIndex);
//调用方法 uploadImageByRetrofit( );
uploadImageByRetrofit(path);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
}
3、上传图片 使用Retrofit上传图片
private void uploadImageByRetrofit(String path) throws UnsupportedEncodingException {
//通过OkHttpClient配置日志拦截器
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new MLanjieqqied())
.build();
创建 Retrofit对象
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://sm.ms/")
.client(client)
.addCallAdapterFactory(RxJava2CallAdapterFactory.createAsync())
.addConverterFactory(GsonConverterFactory.create())
.build();
//文件类型 application/octet-stream
MediaType fileType = MediaType.parse("application/octet-stream");
//要上传的文件对象
File file = new File(path);
//获得接口对象
Album album = retrofit.create(Album.class);
//设置请求体
RequestBody body = RequestBody.create(fileType, file);
String fileName = URLEncoder.encode(file.getName(), "UTF-8");
//创建发送的文件请求体
MultipartBody.Part filePart = MultipartBody.Part.createFormData("smfile", fileName, body);
//文本类型 text/plain
MediaType formatType = MediaType.parse("text/plain");
RequestBody format = RequestBody.create(formatType, "json");
//调用接口中方法
Observable observable = album.uploadImage(filePart, format);
observable.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(Result result) {
System.out.println("onNext " + result.getData().getUrl());
}
@Override
public void onError(Throwable e) {
System.out.println(e.getMessage());
}
@Override
public void onComplete() {
}
});
}
4、接口
public interface Album {
StringBaseUrl="https://sm.ms/";
@Multipart
@POST("https://sm.ms/api/upload")
@Headers({"User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36"})
ObservableuploadImage(@Part MultipartBody.Part filePart, @Part("format") RequestBody format);
}