Upload file in Android with Spring RestTemplate

In my previous post, I created an Android app working with Box.net. It uses Box’s REST APIs to do authentication, browsing, and downloading files on Box.  This post will talk about the upload feature I added to the application.

It turned out to be quite straightforward to do file upload with RestTemplate when it’s done through a multipart form post.  All you need are the following few lines of code to upload a file from your Android,

String fileToUpload = dir.getPath() + File.separator + fileName;
MultiValueMap<String, Object> parts = new LinkedMultiValueMap<String, Object>();
parts.add("file", new FileSystemResource(fileToUpload));
String response = rest.postForObject(uploadUri, parts, String.class, authToken, folderId);

Pretty sleek, right? You can easily bind the response to a Java object via the built-in JSON or XML converter if you are interested in the response after the postForObject() request. An example can be found at AuthActivity in my previous post. Although Spring Mobile for Android does add 1 to 2 MB to an Android application, it’s worthwhile for its power and convenience.

The upload feature will get list of files from the “download” folder using Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).  The files will then be rendered in a ListView, and an AlertDialog will appear when the user clicks on any file in the list to confirm or cancel the download action.  Environment.getExternalStoragePublicDirector() is the recommended way to write public files that will be shared to other applications starting API 8 (Android 2.2). On my test, Environment.DIRECTORY_DOWNLOADS points to /mnt/sdcard/download.  The following is the code which takes care of the application logic I mentioned above,

final File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
String files[] = dir.list();
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, Arrays.asList(files)));
final ListView v = getListView();
v.setOnItemClickListener(new OnItemClickListener() {

	public void onItemClick(final AdapterView<?> parentView, View view, int position,
			long id) {
		final String fileName = (String) parentView.getItemAtPosition(position);
		new AlertDialog.Builder(parentView.getContext()).setTitle("Upload").setMessage("Upload " + fileName +"?")
			.setPositiveButton("OK", new DialogInterface.OnClickListener() {

				public void onClick(DialogInterface di, int arg1) {
					String fileToUpload = dir.getPath() + File.separator + fileName;
					MultiValueMap<String, Object> parts = new LinkedMultiValueMap<String, Object>();
					parts.add("file", new FileSystemResource(fileToUpload));
					RestTemplate rest = RestUtil.getRestTemplate();
					String response = rest.postForObject(uploadUri, parts, String.class, authToken, folderId);
					Log.d(LOG_TAG, response);
					Intent browseIntent = new Intent(parentView.getContext(), BrowseActivity.class);
			    	startActivity(browseIntent);
				}
			}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

				public void onClick(DialogInterface di, int arg1) {
					di.dismiss();
				}
			}).show();
	}

});

The complete code can be found on GitHub at https://github.com/barryku/SpringCloud/tree/master/BoxApp/BoxNetApp.

This entry was posted in Cloud. Bookmark the permalink.

One Response to Upload file in Android with Spring RestTemplate

  1. Pingback: Alexander7

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>