Retrofit上传头像

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

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

猜你喜欢

转载自blog.csdn.net/GaoYiranBlog/article/details/80983972