Reputation: 137
I'm using Sencha Touch 2.1.1. When my app requests a pdf, the server generates the binary data for the pdf, holds it in a buffer and finally spits it out to the browser with
header('Content-Length: '.strlen($this->buffer));
header('Content-disposition: attachment; filename="'.$name.'"');
which, when surfing normally with a web browser, causes one of those 'save or open with' dialogs to be displayed by the browser. With Sencha Touch, I can get a blob from the server, as follows:
var xhr = new XMLHttpRequest();
console.log('new XMLHttpRequest');
var url = 'http://bladhdeblah.com/ws/Download/';
var params = "loginId=" + loginId + "&sId=" + surveyId;
xhr.open('POST', url, true);
xhr.responseType = 'blob';
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onload = function (e) {
if (this.status == 200) {
Ext.Viewport.setMasked(false);
blob = new Blob([this.response], {type: 'application/pdf'});
console.log('new Blob');
var cd = (this.getResponseHeader("Content-disposition"));
var filenameStart = cd.indexOf("\"") + 1;
var filename = cd.substring(filenameStart, cd.length - 1);
console.log('pdf filename is ' + filename);
if (Ext.os.is.Android) {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
}
else {
LRS.util.common.displayAjaxFailure(this.response, 1);
}
};
xhr.send(params)
;
My problem is that phonegap obviously doesn't understand 'new Blob' (logcat on Android shows 'Uncaught TypeError: Illegal constructor') and, as far as I can discover, it is in any case not possible to use phonegap's filewriter to write anything other than plain text (which I have done successfully elsewhere).
I've googled a fair bit, but can't find a solution. With WinJS, I've been able to get the blob and save it using Windows.Storage.Streams.RandomAccessStream.copyAsync, but can't find any similar functionality in phonegap.
I would have thought there must be plenty of people who want their apps to download and save images, mp3s or whatever, so I'm hoping that some phonegap guru out there will be able to point me towards a solution.
I'm aware of phonegap's FileTransfer, but, if I've understood correctly, I would need to provide it with the url of a file saved on the server. I could change the server code so that it saves the pdf, but would prefer not to make such a change.
Incidentally, my app's using a SQLlite database, so maybe a solution is to stick the binary data into there somewhere and display it from there? Trouble is I don't know how to display it.
Upvotes: 3
Views: 1377
Reputation: 173
Instead of using Blob, use WebKitBlobBuilder. Some examples of BlobBuilder can be found here. The link says BlobBuilder is obsolete, but Android (4.1.2 at least) hasn't yet moved to Blob.
Upvotes: 1