javascriptblobdropboxfilereaderdropbox-sdk-js

Javascript Downloading and reading file contents from Dropbox


I am trying to download a file I uploaded as test to Dropbox. The download function works and I am getting the fileblob as well but having trouble to actually read the file contents

function downloadFile() {
            dbx.filesDownload({path: '/_bk_test/test3.json'})
            .then(function(response) {     
                var blob = response.fileBlob;
                var reader = new FileReader();
                reader.addEventListener("loadend", function() {
                    console.log(reader.result); // will print out file content
                });
                reader.readAsText(blob);
            })
            .catch(function(error) {
                console.error(error);
            }); 
}

But I am getting this error as output

PromiseĀ {<pending>}
VM215:11 TypeError: reader.addEventListener is not a function
    at <anonymous>:5:24

This is strange.

But if I store the response.fileBlob in a global variable and then use the reader function, it wont show the TypeError. But I still cant read the file contents.

Either way, these are the issues
1. In a function the FileReader is throwing an exception.
2. Outside the function, the FileReader is not showing the file contents.

PS - Testing in Cordova


Solution

  • Alright, Cordova has a different API

        function downloadFile() {
            dbx.filesDownload({path: '/_bk_test/test3.json'})
            .then(function(response) {     
                var blob = response.fileBlob;
                var reader = new FileReader();
                reader.onloadend = function(evt) {
                    console.log("read success");
                    console.log(evt.target.result);
                };                
                reader.readAsText(blob);
            })
            .catch(function(error) {
                console.error(error);
            }); 
        }