Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
155 views
in Technique[技术] by (71.8m points)

android - Cordova read external archive and play

I am creating an app with cordova for android using plugin file-transfer. The download is going to a certain folder but I can't read the file despite indicating the correct path follows the code

var uri = encodeURI(mypage);
           var fileURL =  cordova.file.externalDataDirectory + "teste.ogg";

           fileTransfer.download(
              uri, fileURL, function(entry) {
                    console.log("download complete: " + entry.toURL());
                  $("#audio-teste").attr('src',fileURL)
                  /*--codigo de teste--*/
            var meuFile = cordova.file.externalDataDirectory;
                  resolveLocalFileSystemURL(meuFile, function(entry) {
                      
                      var readerN = fileSystem.createReader();
                      readerN.readEntries(
                          function (entry) {
                              var arrayN =[];
                        for(var i="0"; i < entry.length; ++i){
                            var entradaN = entry[i].name;
                            arrayN.push(entradaN);
                            //console.log(array);
                            console.log('teste aq' + arrayN);
                        }
                          }
                      )
                      //console.log(entry);
                  });
            
                  /*----*/
                  
              },

              function(error) {
                 console.log("download error source " + error.source);
                 console.log("download error target " + error.target);
                 console.log("download error code" + error.code);
              },

              false, {
                 headers: {
                    "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
                 }
              }
           );
          
          /*----*/
            

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The cordova plugin cordova-plugin-file-transfer is due to be deprecated and its latest npm version fails on iOS.

Therefore these two working functions are purely based on vanilla JS, and thus no need to use extra plugins, besides the standard plugin cordova-plugin-file. Therefore this is compatible with any platform.

https://gist.github.com/jfoclpf/07e52f6bdf9c967449c4bc06af44c94a

I paste here for your convenience:

// for different types of cordovaFileSystem check here: 
// https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file/#where-to-store-files
// or simply type in the console `console.log(cordova.file)`
function downloadFileToDevice (fileurl, filename, cordovaFileSystem, callback) {
  var onerror = (err) => {
    console.error(`Error downloading from ${fileurl} to cordovaFileSystem ${cordovaFileSystem}`, 
    err, new Error(err))
    if (typeof callback === 'function') { callback(Error(err)) }
  }

  var blob = null
  var xhr = new XMLHttpRequest()
  xhr.open('GET', fileurl)
  xhr.responseType = 'blob' // force the HTTP response, response-type header to be blob
  xhr.onload = () => {
    blob = xhr.response // xhr.response is now a blob object
    var DataBlob = blob
    window.resolveLocalFileSystemURL(cordovaFileSystem, (dirEntry) => {
      const sanitizedFilename = filename.replace(/[^a-z0-9.]/gi, '_').toLowerCase() // sanitize filename
      dirEntry.getFile(sanitizedFilename, { create: true }, (file) => {
        file.createWriter((fileWriter) => {
          fileWriter.write(DataBlob)
          if (typeof callback === 'function') { callback(null, cordovaFileSystem + sanitizedFilename) }
        }, (err) => { console.error('Error on file.createWriter'); onerror(err) })
      }, (err) => { console.error('Error on dirEntry.getFile'); onerror(err) })
    }, (err) => { console.error('Error on resolveLocalFileSystemURL'); onerror(err) })
  }
  xhr.onerror = (err) => { console.error('Error on XMLHttpRequest'); onerror(err) }
  xhr.send()
}

An example for downloading a file

downloadFileToDevice('https://example.com/img.jpg',
  'myImg.jpg', 
  cordova.file.cacheDirectory,
  (err, localFilePath) => {
    if (err) {
      console.error('An error occured downloading file:', err)
    } else {
      console.log('Download file with success: ' + localFilePath)
    }
})

Can you try with this? I tried and it works like a charm


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...