Sunil T
Sunil T

Reputation: 11

how to send multi part file from android to rest web service(Spring)?

I want to send Multipart file from android device to rest service which has developed in Spring.

Here is my android code..

 @Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 1 && resultCode == RESULT_OK && data != null && data.getData() != null) {

      Uri filePath = data.getData();

        try {
            bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
            imageView.setImageBitmap(bitmap);

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

        try {

            String path = getPath(filePath);
            //Creating a multi part request
            new MultipartUploadRequest(this,"http://localhost:8080/samplerestfullservice/classtest/upload1")
                    .addFileToUpload(path, "image")//Adding file 
                    .setNotificationConfig(new UploadNotificationConfig())
                    .setMaxRetries(2)
                    .startUpload(); //Starting the upload

        } catch (Exception exc) {
            Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
}


 public String getPath(Uri uri) {
    String[] projection={MediaStore.Images.Media.DATA};
    Cursor cursor=getContentResolver().query(uri,projection,null,null,null);
    if(cursor == null){
        return null;
    }
    int columnIndex= cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    String s=cursor.getString(columnIndex);
    cursor.close();
    return s;
}

And my service code is

@RequestMapping(value = "/upload1", method = RequestMethod.POST, headers = "Content-Type= multipart/form-data" )
@ResponseBody
public void fileUpload(@RequestParam MultipartFile file){       

    System.out.print("Success");

    // rest of the code

}

And I have declared internet permission in manifest.xml but the client request doesn't reach the service.And I don't know is there any compatibility problem.

Please can any one give suggestion.

Thank You.

Upvotes: 0

Views: 854

Answers (1)

Binary Igor
Binary Igor

Reputation: 168

I have wrote lightweight and easy to use library that solves your problem. It is described here https://stackoverflow.com/a/53253933/8849079:)

Upvotes: 1

Related Questions