rxjava打开相册上传图片到sm.ms网站
2019-08-11 本文已影响4人
Ad大成
要上传 先搞清楚图片路径,再搞清楚上传网站的表单提交参数要求
下面是代码
首先,做好请求的基本工作
public interface MyService {
//设置请求头 用户代理 (网站需要必须写)
@Headers("user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36")
//提交方式 和请求的参数
@Multipart
@POST("https://sm.ms/api/upload")
Observable<ResponseBody> getLoad(@Part MultipartBody.Part smfile);
}
接下来就是上传了
public class MainActivity extends AppCompatActivity {
@BindView(R.id.iv_upload)
ImageView ivUpload;
@BindView(R.id.btn_ok)
Button btnOk;
@BindView(R.id.iv_success)
ImageView ivSuccess;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
}
@OnClick(R.id.btn_ok)
public void onViewClicked() {
// 首先一定要申请动态权限
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission
.READ_EXTERNAL_STORAGE}, 1);
} else {
//隐式启动打开相册
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 2 && resultCode == RESULT_OK) {
//获取相册里选中的图片 并且利用内容提供者找到绝对路径
Uri uri = data.getData();
ivUpload.setImageURI(uri);
ContentResolver resolver = getContentResolver();
Cursor cursor = resolver.query(uri, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
String path = cursor.getString(cursor.getColumnIndex("_data"));
File file = new File(path);
uploadImage(file);
}
}
}
private void uploadImage(File file) {
Retrofit retrofit = new Retrofit.Builder().baseUrl("https://sm.ms/")
.addCallAdapterFactory(RxJava2CallAdapterFactory.create()).addConverterFactory
(GsonConverterFactory.create())
.build();
MyService myService = retrofit.create(MyService.class);
请求体构建 选择要请求的类型 以及请求的文件
final RequestBody requsetBody = RequestBody.create(MediaType.parse("image/*"), file);
String name1 = file.getName();
Log.i("tag", "uploadImage: " + name1);
MultipartBody.Part name = MultipartBody.Part.createFormData("smfile", file.getName(),
requsetBody);
请求的参数 按照网站要求name要一致
Observable<ResponseBody> observable = myService.getLoad(name);
observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<ResponseBody>() {
@Override
public void onSubscribe(Disposable d) {
Log.i("tag", "onSubscribe: ");
}
@Override
public void onNext(ResponseBody responseBody) {
try {
//上传成功会返回一个默认json的字符串 解析即可得到上传后的图片网址
String string = responseBody.string();
Gson gson = new Gson();
SuccessResult successResult = gson.fromJson(string, SuccessResult.class);
String url = successResult.getData().getUrl();
Glide.with(MainActivity.this).load(url).into(ivSuccess);
Log.i("tag", "onNext: +" + string);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onError(Throwable e) {
Log.i("tag", "onError: " + e.getMessage());
}
@Override
public void onComplete() {
}
});
}
}