okhttputils上传bitmap图片

上传Resource图片

     try {
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.biaoqian);
            FileOutputStream outputStream = openFileOutput("bitmap.jpg", MODE_PRIVATE);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
          //  bitmap2File(bitmap, new File(getFilesDir(), "bitmap.jpg"));
          //  file = saveFile(bitmap, "bitmap.jpg");
        } catch (Exception e) {
            e.printStackTrace();
        }

        OkHttpUtils
                .post()
                .url("http://123.56.41.81:8080/imgtest/img.do?code=0")
                .addFile("bitmap", "bitmap.jpg", new File(getFilesDir(), "bitmap.jpg"))
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("上传图片测试", e + "");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("上传图片测试", response);
                    }
                });

上传本地File


Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.biaoqian);
//  FileOutputStream outputStream = openFileOutput("bitmap_up_test", MODE_PRIVATE);
//  bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
//  bitmap2File(bitmap, new File(getFilesDir(), "bitmap.jpg"));

 file = saveFile(bitmap, "bitmap.jpg");  //注意上传的文件名称要有后缀 .jpg/.png
 public File saveFile(Bitmap bm, String fileName) throws IOException {// TODO: 2017/1/7
        FileOutputStream fileOutputStream = openFileOutput(fileName, MODE_PRIVATE);
        BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
        bm.compress(Bitmap.CompressFormat.JPEG, 100, bos);
        bos.flush();
        bos.close();
        File file = new File(getFilesDir(), fileName);
        Log.e("myCaptureFile", file.getPath());
        return file;
    }
  OkHttpUtils
                .post()
                .url("http://123.56.41.81:8080/imgtest/img.do?code=0") 
                .addFile("bitmap", "bitmap.jpg", file)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("上传图片测试", e + "");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("上传图片测试", response);
                    }
                });

你可能感兴趣的:(okhttputils上传bitmap图片)