Cordova: submit multipart form with additional parameters

With the Cordova plugin File-Transfer you can submit a multipart form with additional parameters. To read an image file as a binary string, you can use the HTML5 FileReader syntax from the File API by using the Cordova plugin File.

For instance, the following example uses Idol On Demand‘s APIs to analyze images for barcodes.

Add the required plugins.
$cordova plugin add org.apache.cordova.console
$cordova plugin add org.apache.cordova.file
$cordova plugin add org.apache.cordova.file-transfer

This is the code to submit a multipart form in Cordova. Note that the additional parameters are added to the form by using the options.params property with an associative array of parameters.

var formURL = "https://api.idolondemand.com/1/api/sync/readbarcode/v1";
var encodedURI = encodeURI(formURL);
// add additional parameters 'file' and 'apikey' to the multipart form
var options = new FileUploadOptions();
options.fileKey = "file";
// strip the filename from the full path
options.fileName = fileURI.substr(fileURI.lastIndexOf('/') + 1);
var imgData = readFileAsBinaryString(fileURI);
options.params = { 'apikey': apikey, 'file': imgData };
// create the FileTransfer object
var ft = new FileTransfer();
// submit the multipart form
ft.upload(fileURI, encodedURI, fnOnSuccess, fnOnError, options, false);

The readFileAsBinaryString(file) is implemented like this:

function readFileAsBinaryString(file) {
 console.log("readFileAsBinaryString(: "+file+")");
 var reader = new FileReader();
 reader.onloadend = function(e) {
  console.log("Successfully read file as binary string");
  var imgData = e.target.result;
  return imgData;
 };
 reader.onerror = function(e) {
  console.log("Error while reading file as binary string: "+e.target.error.code);
 };
 reader.readAsBinaryString(file);
}

One thought on “Cordova: submit multipart form with additional parameters

Leave a Reply

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