Android okHttp上传单张或多张照片
1.利用LruCache、DiskLruCache实现图片的加载,避免OOM
2.引用开源库https://github.com/pengjianbo/GalleryFinal,实现从相册中选择图片、拍照进而进行上传,图片上传可以
private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
private final OkHttpClient client = new OkHttpClient();
private void uploadImg() { // mImgUrls为存放图片的url集合 MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM); for (int i = 0; i <mImgUrls.size() ; i++) { File f=new File(mImgUrls.get(i)); if (f!=null) { builder.addFormDataPart("img", f.getName(), RequestBody.create(MEDIA_TYPE_PNG, f)); } }//添加其它信息 // builder.addFormDataPart("time",takePicTime); // builder.addFormDataPart("mapX", SharedInfoUtils.getLongitude()); // builder.addFormDataPart("mapY",SharedInfoUtils.getLatitude()); // builder.addFormDataPart("name",SharedInfoUtils.getUserName()); MultipartBody requestBody = builder.build(); //构建请求 Request request = new Request.Builder() .url(Constant.BASE_URL)//地址 .post(requestBody)//添加请求体 .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { System.out.println("上传失败:e.getLocalizedMessage() = " + e.getLocalizedMessage()); } @Override public void onResponse(Call call, Response response) throws IOException { System.out.println("上传照片成功:response = " + response.body().string()); ToastCustom.makeText(PictureListActivity.this, "上传成功", Toast.LENGTH_LONG).show(); } }); }
静以修身,俭以养德。
posted on 2016-09-12 16:33 miaozhenzhong 阅读(1001) 评论(0) 编辑 收藏 举报