1

I am trying to Upload file along with JSON post body. I have tried something like this:

requestBody  = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart("data", uploadFileName[1], RequestBody.create(MEDIA_TYPE_JPEG, file))
            .addFormDataPart("name", uploadFileName[1])
            .addFormDataPart("body",postBody)
            .build();

NOTE: Above code works if I want to upload file without post body by removing

   .addFormDataPart("body",postBody)

also I have tried to create ByteOutputArray of both file and post body and tried to create a ResquestBody.

Something like this:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write((boundaryStr).getBytes("UTF-8"));
baos.write(("Content-Disposition: attachment;filename=\"" + uploadFileName + "\"\r\n").getBytes("UTF-8"));
baos.write(("Content-Type: application/octet-stream\r\n\r\n").getBytes("UTF-8"));
byte[] buffer = new byte[102400];// 100KB
int read = imageInputStream.read(buffer);
while (read >= 0) {
    baos.write(buffer);
    read = imageInputStream.read(buffer);
}
baos.write(("\r\n").getBytes("UTF-8"));
baos.write((boundaryStr).getBytes("UTF-8"));
baos.write(("Content-Disposition: attachment; name=\"" + fileNameText + "\"\r\n\r\n").getBytes("UTF-8"));
baos.write((postData).getBytes("UTF-8"));
baos.write(("\r\n").getBytes("UTF-8"));
baos.write(("--" + boundary + "--\r\n").getBytes("UTF-8"));
baos.flush();

MediaType MEDIA_TYPE_JPEG  = MediaType.parse(fileType);
RequestBody requestBody = RequestBody.create(MEDIA_TYPE_JPEG,baos.toByteArray());

But nothing is working. Please help.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291

2 Answers2

0

Try the code below:

private void chooseImageFile(){
        Intent intent = new Intent() ;
        intent.setType("image/*") ;
        intent.setAction(Intent.ACTION_GET_CONTENT) ;
        startActivityForResult(Intent.createChooser(intent, "Select Image"), PICK_IMAGE_REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null){
            Uri imagepath = data.getData() ;
            try {
                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imagepath) ;
                uploadimage.setImageBitmap(bitmap);

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private String getStringImage(Bitmap bitmap){
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream() ;
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream) ;
        byte[] imagebyte = byteArrayOutputStream.toByteArray() ;
        String encodeString = Base64.encodeToString(imagebyte, Base64.DEFAULT) ;
        return encodeString ;
    }

private void callImageUpload() {
        String image_name = imagename.getText().toString().trim() ;
        String bitmap_string = getStringImage(bitmap) ;
        OkHttpClient image_upload_client = new OkHttpClient() ;
        RequestBody postbody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("image", bitmap_string)
                .addFormDataPart("name", image_name)
                .build() ;

        Request request = new Request.Builder().url(url).post(postbody).build() ;
        setProgressDialouge();
        image_upload_client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                progressDialog.dismiss();
                String json_string = response.body().string() ;
                try {
                    JSONObject main_obj = new JSONObject(json_string);
                    final String msg = main_obj.getString("response");

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
                        }
                    });
                }
                catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
Imtiaz Abir
  • 731
  • 7
  • 12
  • This code will only upload image. Can't see JSON post body going in request body. I need to send JSON post body along with file in API – Prashant Sethi Jan 03 '18 at 11:12
  • This answer given here: https://stackoverflow.com/questions/34179922/okhttp-post-body-as-json might help. – Imtiaz Abir Jan 03 '18 at 11:35
0
 @Multipart
    @POST("/api/index.php?tag=sendFile")
    Call<Object> sendCurrentFileAPI(
                                    @Part("file") RequestBody  designation, @Part MultipartBody.Part file);

and I am using following method for uploading file in my Activity

 MultipartBody.Part multipartBody = null;
    try {
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), uploadingCurrentFile);

        multipartBody = MultipartBody.Part.createFormData("file", uploadingCurrentFile.getName(), requestFile);
    } catch (Exception e) {
        e.printStackTrace();
    }

    RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain"), requestBody +"");

    mService.sendCurrentFileAPI( selectedDesignationValueRequestBody, multipartBody).enqueue(new Callback<Object>() {
        @Override
        public void onResponse(@NonNull Call<Object> call, @NonNull Response<Object> response) {

            if (response.isSuccessful()) {


        }

        @Override
        public void onFailure(@NonNull Call<Object> call, @NonNull Throwable t) {



        }
    });

Also I am using https://github.com/spacecowboy/NoNonsense-FilePicker for file picker

Ameer
  • 2,709
  • 1
  • 28
  • 44