Uncaught TypeError: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'

前端 未结 4 2234
名媛妹妹
名媛妹妹 2021-02-02 08:18

I\'ve got a problem with a javascript Filereader which returns the error Uncaught TypeError: Failed to execute \'readAsDataURL\' on \'FileReader\': parameter 1 is not of type \'

4条回答
  •  心在旅途
    2021-02-02 08:41

    You do not need to create a new Image and you should be listening for the loadendevent of the readAsDataURLmethod, which will provide you with a base64 encoded string of your data.

    FileReader.readAsDataURL()

    The readAsDataURL method is used to read the contents of the specified Blob or File. When the read operation is finished, the readyState becomes DONE, and the loadend is triggered. At that time, the result attribute contains the data as a URL representing the file's data as a base64 encoded string.

    Also make sure you actually have a file, and maybe even check the file.type. Since you are trying to do something with an image, why not check if you have an image. Which in no way is some kind of validation, but if it is not an image, you may not need to show anything or do anything.

    Here is an example.

    var img = $('img');
    img.css('display', 'none');
    
    $('#upload-button').click(function(){
      $('#my-custom-design-upload').trigger('click');                 
      return false;
    });
    
    function readfichier(e) {
      if(window.FileReader) {
        var file  = e.target.files[0];
        var reader = new FileReader();
        if (file && file.type.match('image.*')) {
          reader.readAsDataURL(file);
        } else {
          img.css('display', 'none');
          img.attr('src', '');
        }
        reader.onloadend = function (e) {
          img.attr('src', reader.result);
          img.css('display', 'block');
        }
      }
    }
    
    document.getElementById('my-custom-design-upload').addEventListener('change', readfichier, false);
    
    
    Insérer votre image

提交回复
热议问题