Nils Fett
Nils Fett

Reputation: 385

Using createObjectURL from local file system file entry results in broken file

My app is a cordova app. I try to do the following for the platform browser. I know the descriped problem will not occour on real devices platforms.

I try do do the the following:

  1. Download image file via XMLHttpRequest
  2. Display image via createObjectURL using blob from XMLHttpRequest response
  3. Write the file to local File System ( using cordova-plugin-file to make fileSystem API available in Firefox)
  4. Display image via createObjectURL using blob from file in local Filesystem

I can create a blob from saved file, but the image ist broken after that.

This is the code:

    var filesystem;
    var downloaddir;
    var filename = 'e44498f0b0964152632bd0c82342914b859c543e.jpeg'
    var downloadurl = 'http://adomain.com/public/content_images/'+filename;


    function download(){
      filesystem.root.getFile(
        '/ressources/'+filename, 
        { create: true, exclusive: false }, 
        function (fileEntry) {  

          var oReq = new XMLHttpRequest();

          oReq.open("GET", downloadurl, true);
          oReq.responseType = "blob";
          oReq.onload = function (oEvent) {
            var blob = oReq.response;
            if (blob) {         
              fileEntry.createWriter(function (fileWriter) {                        
                fileWriter.onwriteend = function (e) {
                  console.log(fileEntry.toURL());// Works in Chrome and Firefox, but file URIs cannot be used for security reasons. So image is not displayed if this RUL is used in image src attribute
                  console.log(window.URL.createObjectURL(blob));// work in chrome and firefox. This is what I like to have in the end but using a file.

                  // Now I want to use the file and transform it in a objectURL, this is where I struggle
                  fileEntry.file(function(file){
                    console.log(window.URL.createObjectURL(file));// works in chrome bot not in firefox. Firefox says :"TypeError: Argument 1 is not valid for any of the 1-argument overloads of URL.createObjectURL."

                    var readerBlob = new FileReader();                              
                    readerBlob.onload = function(event){                                    
                      var blob = new Blob([event.target.result], {type: 'image/jpg'});
                      console.log(window.URL.createObjectURL(blob));// blob uri will be created, but image is broken. Here I want to have a working objectURL that work for Chrome and Firefox           
                    };
                    readerBlob.readAsBinaryString(file);
                  });

                };
                fileWriter.onerror = function (e) {
                };
                fileWriter.write(blob);
              });

            } else console.error('we didnt get an XHR response!');
          };
          oReq.send(null);
        }, 
        function (error) {
          console.log('error creating file');
          console.log(error);
        }
      );
    }

    document.addEventListener("deviceready", function(){
      window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
      window.requestFileSystem(window.TEMPORARY, 10 * 1024*1024, function (fs) {
        filesystem = fs;            
        filesystem.root.getDirectory(
          '/ressources/',
          {create:true}, 
          function(dirEntry){
            console.log('download dir created');
            downloaddir = dirEntry;
            download();
          },
          function(error){
          }
        );
      });
    }, false);

Upvotes: 0

Views: 5008

Answers (1)

Nils Fett
Nils Fett

Reputation: 385

Found the error: I had to read the file with readAsArrayBuffer. That does the trick. So here the working code, maybe it helps someone:

    var filesystem;
    var downloaddir;
    var filename = 'e44498f0b0964152632bd0c82342914b859c543e.jpeg'
    var downloadurl = 'http://adomain.com/public/content_images/'+filename;


    function download(){
      filesystem.root.getFile(
        '/ressources/'+filename, 
        { create: true, exclusive: false }, 
        function (fileEntry) {  

          var oReq = new XMLHttpRequest();

          oReq.open("GET", downloadurl, true);
          oReq.responseType = "blob";
          oReq.onload = function (oEvent) {
            var blob = oReq.response;
            if (blob) {         
              fileEntry.createWriter(function (fileWriter) {                        
                fileWriter.onwriteend = function (e) {
                  console.log(fileEntry.toURL());// Works in Chrome and Firefox, but file URIs cannot be used for security reasons. So image is not displayed if this RUL is used in image src attribute
                  console.log(window.URL.createObjectURL(blob));// works in chrome and firefox. This is what I like to have in the end but using a file.

                  // Now I want to use the file and transform it in a objectURL, this is where I struggle
                  fileEntry.file(function(file){
                    //console.log(window.URL.createObjectURL(file));// works in chrome bot not in firefox. Firefox says :"TypeError: Argument 1 is not valid for any of the 1-argument overloads of URL.createObjectURL."

                    var readerBlob = new FileReader();                              
                    readerBlob.onload = function(event){                                    
                      console.log(event.target.result);

                      var blob = new Blob([event.target.result], {type: 'image/jpg'});
                      console.log(window.URL.createObjectURL(blob));// This URL will work in Chrome and Firefox          
                    };
                    readerBlob.readAsArrayBuffer(file);
                  });

                };
                fileWriter.onerror = function (e) {
                };
                fileWriter.write(blob);
              });

            } else console.error('we didnt get an XHR response!');
          };
          oReq.send(null);
        }, 
        function (error) {
          console.log('error creating file');
          console.log(error);
        }
      );
    }

    document.addEventListener("deviceready", function(){
      window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
      window.requestFileSystem(window.TEMPORARY, 10 * 1024*1024, function (fs) {
        filesystem = fs;            
        filesystem.root.getDirectory(
          '/ressources/',
          {create:true}, 
          function(dirEntry){
            console.log('download dir created');
            downloaddir = dirEntry;
            download();
          },
          function(error){
          }
        );
      });
    }, false);

Upvotes: 1

Related Questions