Retrofit上传头像

本文介绍如何使用Retrofit框架实现图片上传功能。通过创建Retrofit实例并定义接口,使用MultipartBody上传文件到服务器。文章还展示了处理响应及异常的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Api:

 @Multipart
    @POST("file/upload")
    Call<Upload> uploadPhoto(@Query("uid") String mobile, @Part MultipartBody.Part part);

主要实现的代码如下: 


    RetrofitManager aDefault = RetrofitManager.getDefault();

    ILoginApi iLoginApi = aDefault.create(ILoginApi.class);

    File file = getResourcesFile();

        RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);

        MultipartBody.Part part = MultipartBody.Part.createFormData("file", file.getName(), requestBody);

        Call<Upload> uploadCall = iLoginApi.uploadPhoto("15075", part);

        uploadCall.enqueue(new Callback<Upload>() {
            @Override
            public void onResponse(Call<Upload> call, Response<Upload> response) {
                Upload upload = response.body();
                if(upload != null){

                    Toast.makeText(MainActivity.this, "成功", Toast.LENGTH_SHORT).show();

                }
                else{

                    Log.e("tag", "失败" + upload.toString());
                    Toast.makeText(MainActivity.this, "错误", Toast.LENGTH_SHORT).show();

                }
            }

            @Override
            public void onFailure(Call<Upload> call, Throwable t) {

                Log.e("tag", "失败" + t.getMessage());
                Toast.makeText(MainActivity.this, "错误", Toast.LENGTH_SHORT).show();

            }
        });

public File getResourcesFile() {

        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);

        File file = new File(getFilesDir().getAbsolutePath());
        if(!file.exists()){

            file.mkdirs();

        }

        File file1 = new File(file, "photo.png");

        FileOutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(file1);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return file1;
    }

最后再次刷新接口就能看见你上传的图片啦!!!
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值