简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM