Convert data file to blob

后端 未结 3 1779

How to get a blob?

HTML:


JavaScript:

function previewFile()          


        
相关标签:
3条回答
  • 2021-01-03 22:41

    As pointed in the comments, file is a blob:

    file instanceof Blob; // true
    

    And you can get its content with the file reader API https://developer.mozilla.org/en/docs/Web/API/FileReader

    Read more: https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications

    var input = document.querySelector('input[type=file]');
    var textarea = document.querySelector('textarea');
    
    function readFile(event) {
      textarea.textContent = event.target.result;
      console.log(event.target.result);
    }
    
    function changeFile() {
      var file = input.files[0];
      var reader = new FileReader();
      reader.addEventListener('load', readFile);
      reader.readAsText(file);
    }
    
    input.addEventListener('change', changeFile);
    <input type="file">
    <textarea rows="10" cols="50"></textarea>

    0 讨论(0)
  • async function FileToString (file) {
        try {
            let res = await file.raw.text();
            console.log(res);
        } catch (err) {
            throw err;
        }
    }
    
    0 讨论(0)
  • 2021-01-03 23:02

    A file object is an instance of Blob but a blob object is not an instance of File

    new File([], 'foo.txt').constructor.name === 'File' //true
    new File([], 'foo.txt') instanceof File // true
    new File([], 'foo.txt') instanceof Blob // true
    
    new Blob([]).constructor.name === 'Blob' //true
    new Blob([]) instanceof Blob //true
    new Blob([]) instanceof File // false
    
    new File([], 'foo.txt').constructor.name === new Blob([]).constructor.name //false
    

    If you must convert a file object to a blob object, you can create a new Blob object using the array buffer of the file. See the example below.

    let file = new File(['hello', ' ', 'world'], 'hello_world.txt', {type: 'text/plain'});
    //or let file = document.querySelector('input[type=file]').files[0];
    let reader = new FileReader();
    reader.onload = function(e) {
        let blob = new Blob([new Uint8Array(e.target.result)], {type: file.type });
        console.log(blob);
    };
    reader.readAsArrayBuffer(file);
    
    0 讨论(0)
提交回复
热议问题