Jannik Weichert
Jannik Weichert

Reputation: 1673

Saving BLOB as .txt works but not for other types

I'm trying to save a blob in PhoneGap - But it's the normal File API. I get the blob from my server via XHR and it works fine. If i create a img tag and set the src to my blob, the image is shown on my screen.

I can save the blob to the filesystem, but trying to open them fails. Only .txt works correctly. Do i have to set the datatype anywhere?

My download and save functions can be found here: http://pastebin.com/GrA2tRQt

In short I do a fileWriter.write(this.response);

Thank's for any help in advance!

Upvotes: 2

Views: 860

Answers (1)

Jannik Weichert
Jannik Weichert

Reputation: 1673

I solved it myself. Here's the solution for those who are interested in: Just set the responsetype to arraybuffer.

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
    if (xhr.readyState == 4) { // complete.
        if (xhr.status >= 200 && xhr.status < 300) {
            var data = this.response;
            successCallback(data, fileName);
        } else {
            // response not successfull
            var error = /<d:error/;
            if (error.test(xhr.responseText)) {
                console.log("ResponseText: " + xhr.responseText);
            } else {
                console.log("Kein ResponseText vorhanden");
            }
        }
    }
};
xhr.open("GET", url, true);
xhr.responseType = 'arraybuffer';
xhr.setRequestHeader("Authorization", "Basic " + authToken);
xhr.send();

Then you can save it in your successCallback as following:

performSave = function (data, filename) {
    console.log("perform Save");
    console.log(data);
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {
        fileSystem.root.getFile(filename, { create: true }, function (fileEntry) {
            fileEntry.remove(
                fileEntry.createWriter(function (fileWriter) {
                fileWriter.onwriteend = function (e) {
                    cloud.functions.performSaveSuccess();
                };
                fileWriter.onerror = function (e) {
                    cloud.functions.performSaveError(e);
                };
                fileWriter.write(data);
            }, errorCallback));
        }, errorCallback);
    })
}

Hope this helps anyone

Upvotes: 2

Related Questions