Android打开相册并上传图片至服务器

Android图片打开上传

打开相册

大多的安卓程序都需要上传头像或者一些图片,给大家一些我这几天遇到图片上传问题的经验。
首先这是我的个人中心页面
Android打开相册并上传图片至服务器_第1张图片
点击上面的图片,会出现我们相册的选项,点击进入以后可以选择图片。

 @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        uName = (TextView) getActivity().findViewById(R.id.uName);
        userInner = (UserInner) getActivity().getIntent().getSerializableExtra("userInner");
        uName.setText(userInner.getName());
        draweeView = (SimpleDraweeView) getActivity().findViewById(R.id.photo);
        if(userInner.getPhoto()!=null){
            Uri uri = Uri.parse(userInner.getPhoto());
            draweeView.setImageURI(uri);
        }
        draweeView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(i,GETIMG);
            }
        });

        list = (ListView) getActivity().findViewById(R.id.list);
        cancel = (Button) getActivity().findViewById(R.id.cancel) ;
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(),MainActivity.class);
                startActivity(intent);
            }
        });
        list.setAdapter(new ItemAdapter(getActivity(),Arrays.asList(items)));
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode){
            case TAKEPHOTO:
                if(resultCode ==RESULT_OK){
                    draweeView.setImageURI(imageUri);
                }
                break;
            case GETIMG:
                //打开相册并选择照片,这个方式选择单张
// 获取返回的数据,这里是android自定义的Uri地址
                Uri selectedImage = data.getData();
                String[] filePathColumn = { MediaStore.Images.Media.DATA };
// 获取选择照片的数据视图
                if(selectedImage!=null){
                    Cursor cursor = getActivity().getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                    cursor.moveToFirst();
// 从数据视图中获取已选择图片的路径
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    picturePath = cursor.getString(columnIndex);
                    cursor.close();
// 将图片显示到界面上

                    NetworkUtil.upLoadImg("http://39.106.81.100:9999/firefly/user/upload",userInner.getId().toString(),picturePath, BasMsg.class, new INetCallback() {
                        @Override
                        public void onSuccess(final BasMsg msg) {
                            draweeView.setImageURI(picturePath);
                        }
                    });

                }
                break;

                default:break;
        }
    }

上面关于fesco图片框架的问题,大家可以去官网看一下Fesco官网
Android必用的图片加载框架,还可以设置圆角,形状等。

上传至服务器

那么我们引入okHttp3—火爆的网络库以后,就可以写好get,post等方法进行上传数据和文件了。

GET

static OkHttpClient client  = new OkHttpClient();
    static Gson gson = new Gson();
    public static  void getMethod(String url,final Class cls,final INetCallback callback)
    {

        final Request request = new Request.Builder()
                .url(url)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if(response.isSuccessful()){//回调的方法执行在子线程。
                    callback.onSuccess(gson.fromJson( response.body().string(),cls));

                }
            }
        });


    }

POST

public static void postMethod(String url, HashMap map, final Class cls, final INetCallback callback){
FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
for (String key:map.keySet())
{
formBody.add(key,map.get(key));
}
Request request = new Request.Builder()//创建Request 对象。
.url(url)
.post(formBody.build())//传递请求体
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {

            Log.d("Network","failure");
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            if(response.isSuccessful()){
                callback.onSuccess(gson.fromJson(response.body().string(),cls));
            }
        }
    });
}

POST上传图片(MultipartFile)

public static  void upLoadImg(String url, String uid ,String imgPath, final Class cls, final INetCallback callback){
         final String imageType = "multipart/form-data";
         File file = new File(imgPath);
        RequestBody fileBody = RequestBody.create(MediaType.parse("image/*"), file);
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("img",file.getName(),fileBody)
                .addFormDataPart("uid", uid)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        client.newBuilder().readTimeout(10000, TimeUnit.MILLISECONDS).build().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
               Log.d("Timeout","超时超时");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if(response.isSuccessful()){
                    callback.onSuccess(gson.fromJson(response.body().string(),cls));
                }
            }
        });


    }

你可能感兴趣的:(Android之路)