上传文件(图片)

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);
        }
    });


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值