简体   繁体   中英

Is it possible to download data via Javascript and then reference that data via a file path?

I would like to do this:

  1. Download data from a server via Javascript (this I know I can do)
  2. Store it on the disk (I know I can do this with IndexedDB)
  3. Reference that data as a file path. (Example: If I download an mp3, I'd like it to be able to pass it into an HTML5 audio tag as "foo.mp3")

Is #3 possible?

I know I can just use base64 and make a data URI, but that is slow and (at least for audio) doesn't appear to work on Android nor iOS (I've tested this with plain HTML5 audio tags and SoundManager2).

Note: I am only interested in cross browser, cross platform solutions.

Ostensibly you should be able to do the following:

  • Read the blob back out of the database
  • Use URL.createObjectURL() to construct a URL for the blob
  • Assign the URL to the audio element
  • Optional: URL.revokeObjectURL() to release the blob when it's no longer needed (eg if the audio element is given a new URL)

For example:

<!DOCTYPE html>
<title>IndexedDB / Blob / URL Example</title>
<p>Select audio file here: <input type=file>
<p>Then play here: <audio controls></audio>
<script>
// When a file is selected...
document.querySelector('input[type="file"]').addEventListener('change', function(e) {
  var file = e.target.files[0];

  // Open the database connection.
  var open = indexedDB.open('blob-test');
  open.onupgradeneeded = function() {
    // Define the database schema if necessary.
    var db = open.result;
    var store = db.createObjectStore('files');
  };
  open.onsuccess = function() {
    var db = open.result;
    var key = 1;

    // Write file to DB
    var tx = db.transaction('files', 'readwrite');
    var store = tx.objectStore('files');
    store.put(file, key);

    // Later, read file back out of DB
    var tx2 = db.transaction('files');
    var store2 = tx2.objectStore('files');
    var request = store2.get(key);
    request.onsuccess = function(e) {
      // Got the file!
      var file = request.result;
      // Construct a URL for it
      var url = URL.createObjectURL(file);
      // Update audio element with the URL
      document.querySelector('audio').src = url;
    };
  };
});
</script>

.. but you'll still want to test everywhere. There are bugs recently fixed in eg Chrome on Android that would have affected this (eg https://crbug.com/227476 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM