Performing a Form File Upload using BlackBerry Dynamics APIs
Jump straight to the sample on Github here: GDHttpClientFileUpload Sample
The BlackBerry Dynamics SDK includes APIs that allow for secure network communication between an app and a server located within your corporate network. If you are not yet familiar on how that works take a look at our getting started guide for an architectural overview.
In this article I’m going to explain how you can use these APIs to upload a file using HTML Forms based submission.
The first thing you'll need is a web server ready to accept your file upload. Since you’re reading this, you likely have one set up that you want to use. But if not, the free Post Test Sever can be used. It’s an online service that allows you to make HTTP GET and POST requests, records the submitted data and allows you to view it afterwards. This is what the sample project makes use of.
Next, you'll create some code that uses GDHttpClient to make an HTTP connection. A boundary is used to separate the multiple parts of the form data. The networking code looks like this:
The key element in the code above is the UploadContentProducer. The UploadContentProducer takes care of adding the files that will be uploaded along with any other form elements that make up the form. The UploadContentProducer code looks like this:
For simplicity, the sample code uses the String in the FILE_CONTENTS variable as the content of the file that is uploaded. In your application the file would likely reside on the file system of the device, so you’d need to swap that constant for the contents of your file.
The addFilePart method accepts the file name and file contents and adds that to the request. The example stores the file contents in a byte array in RAM, which will work fine for small to medium sized files. If you need to upload large files, a buffering solution should be implemented instead.
The addFormPart method accepts the parameter names and values for all non-file elements of your form. Call this method to add each element.
Try the sample yourself to see it in action. You can clone the project from Github here: GDHttpClientFileUpload Sample