上传头像

本文介绍使用Retrofit进行网络请求及图片上传的具体实现,包括定义Service接口、创建Retrofit实例、执行请求和响应处理等关键步骤。同时,展示了如何在Android应用中通过相机或相册选择图片并上传至服务器。

Service层

public interface BaseService {
    @POST
    Call<ResponseBody> post(@Url String url, @QueryMap Map<String, String> map);
    //上传
    @Multipart
    @POST
    Call<ResponseBody> uploadPic(@Url String url, @HeaderMap Map<String, String> map, @Part MultipartBody.Part part);
}

工具类

public class RetrofitUtil {

    public RetrofitUtil post(String url, Map<String,String>map){
        BaseService service = getService();
        Call<ResponseBody> call = service.post(url, map);
        doCall(call);
        return this;
    }

    private BaseService getService() {
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl("http://172.17.8.100/small/")
                .build();
        return retrofit.create(BaseService.class);
    }

    public RetrofitUtil upload(String url,Map<String,String>map,String path){
        MediaType mediaType = MediaType.parse("multipart/form_data;charset = utf-8");
        File file = new File(path);
        RequestBody body = RequestBody.create(mediaType, file);
        MultipartBody.Part part = MultipartBody.Part.createFormData("image", file.getName(), body);
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://172.17.8.100/small/")
                .build();
        BaseService service = retrofit.create(BaseService.class);
        Call<ResponseBody> call = service.uploadPic(url, map, part);
        doCall(call);
        return this;
    }

    private void doCall(Call<ResponseBody> call) {
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    if (httpListener != null){
                        httpListener.success(response.body().string());
                    }
                    if (streamListener != null){
                        streamListener.success(response.body().byteStream());
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                if (httpListener != null){
                    httpListener.fail(t.getMessage());
                }
                if (streamListener != null){
                    streamListener.fail(t.getMessage());
                }
            }
        });
    }

    private HttpListener httpListener;

    public void setHttpListener(HttpListener httpListener) {
        this.httpListener = httpListener;
    }

    public interface HttpListener{
        void success(String data);
        void fail(String error);
    }

    private HttpStreamListener streamListener;

    public void setStreamListener(HttpStreamListener streamListener) {
        this.streamListener = streamListener;
    }

    public interface HttpStreamListener{
        void success(InputStream inputStream);
        void fail(String error);
    }
}

主页面

public class MainActivity extends AppCompatActivity {

    //sd路径
    private static String path = "/sdcard/myHead";
    private ImageView main_image;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        main_image = findViewById(R.id.main_image);
        //相机
        findViewById(R.id.main_ji).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
                        "head.jpg")));
                startActivityForResult(intent,2);
            }
        });
        //相册
        findViewById(R.id.main_ce).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_PICK, null);
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"image/*");
                startActivityForResult(intent,1);
            }
        });
    }
    //调用裁剪
    public void jian(Uri uri){
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri,"image/*");
        intent.putExtra("crop","true");
        intent.putExtra("aspectX",1);
        intent.putExtra("aspectY",1);
        intent.putExtra("outputX",127);
        intent.putExtra("outputY",127);
        intent.putExtra("scale",true);
        //人脸识别
        intent.putExtra("noFaceDetection",false);
        intent.putExtra("return-data",true);
        startActivityForResult(intent,3);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case 1:
                if (resultCode == RESULT_OK){
                    jian(data.getData());
                }
                break;
            case 2:
                if (resultCode == RESULT_OK){
                    File temp = new File(Environment.getExternalStorageDirectory()
                            + "/head.jpg");
                    jian(Uri.fromFile(temp));
                }
                break;
            case 3:
                if (data != null){
                    Bundle extras = data.getExtras();
                    if (extras == null){
                        return;
                    }
                    Bitmap head = extras.getParcelable("data");
                    if (head != null){
                        main_image.setImageBitmap(head);
                        String fileName = path + "/head.jpg";
                        //上传到服务器
                        upLoad(fileName);
                    }
                }
                break;
        }
    }

    private String UP_URL = "user/verify/v1/modifyHeadPic";

    private void upLoad(String sdPath) {
        Map<String, String> map = new HashMap<>();
        map.put("userId","558");
        map.put("sessionId","1557061331452558");
        new RetrofitUtil().upload(UP_URL,map,sdPath).setHttpListener(new RetrofitUtil.HttpListener() {
            @Override
            public void success(String data) {
                Toast.makeText(MainActivity.this,data,Toast.LENGTH_LONG).show();
            }

            @Override
            public void fail(String error) {
                Toast.makeText(MainActivity.this,error,Toast.LENGTH_LONG).show();
            }
        });
    }
    //保存到SD卡
    private void setImageToSD(Bitmap mBitmap){
        String s = Environment.getExternalStorageState();
        if (!s.equals(Environment.MEDIA_MOUNTED)){
            return;
        }
        FileOutputStream outputStream = null;
        File file = new File(path);
        file.mkdirs();
        String fileName = path + "/head.jpg";
        try {
            outputStream = new FileOutputStream(fileName);
            mBitmap.compress(Bitmap.CompressFormat.JPEG,100,outputStream);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }finally {
            try {
                outputStream.flush();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值