ApiService :
@Multipart
@POST("放接口地址")
Call<goodbean) get(@Part MultipartBody.Part file);
跳转到相册
Intent intent=new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(intent,2);
回调方法里
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
File file1=null;
Bitmap bitmap=null;
//取出照片
Uri uri = data.getData();
try {
bitmap=MediaStore.Images.Media.getBitmap(getContentResolver(),uri);
} catch (IOException e) {
e.printStackTrace();
}
//转换成file格式
String path=Environment.getExternalStorageDirectory()+"/zhangna";
File file=new File(path);
//判断文件是否存在
if (!file.exists()){
file.mkdir();
}
file1=new File(file,"1234.png");
try {
//用流写入
BufferedOutputStream bo=new BufferedOutputStream(new FileOutputStream(file1));
//压缩
bitmap.compress(Bitmap.CompressFormat.JPEG,100,bo);
//刷新
bo.flush();
//关闭流
bo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//上传图片
sc(file1);
}
上传的方法
private void sc(File file11) {
RequestBody body = RequestBody.create(MediaType.parse("application/otcet-stream") , file11);
//文件的key就是image
MultipartBody.Part part = MultipartBody.Part.createFormData("image" , file11.getName() , body);
Log.d("MainActivity", "part:" + part);
// 走接口
ApiService service = RetriftUtils.getinstance(Api.url, ApiService.class);
Call<GoodsBean> call = service.get(part);
call.enqueue(new Callback<GoodsBean>() {
@Override
public void onResponse(Call<GoodsBean> call, Response<GoodsBean> response) {
GoodsBean bean = response.body();
String s = bean.getHeadPath();
img.setImageURI(Uri.parse(s));
Log.d("MainActivity", bean.getMessage());
}
@Override
public void onFailure(Call<GoodsBean> call, Throwable t) {
Log.d("MainActivity", "t:" + t);
}
});
}