Home > Enterprise >  Uploaded file show error message, how to solve?
Uploaded file show error message, how to solve?

Time:12-25

I have created a place holder with image that able to upload file then i create a condition that the file size recommended to be 100 kb or more and less than 1mb size upload

var uploadField = document.getElementById("myImg");

uploadField.onchange = function() {
  // 1000000 = 1MB 
  if (this.files[0].size > 1000000) {
    alert("File is too big!");
    this.value = "";
  } else if (this.files[0].size < 100000) {
    alert("File not recommended size!");
    this.value = "";
  }
};

$('#myImg').change(function(event) {
  // var tmppath = URL.createObjectURL(event.target.files[0]);
  $("img#output").fadeIn("fast").attr('src', URL.createObjectURL(event.target.files[0]));

  // $("#disp_tmp_path").html("Temporary Path(Copy it and try pasting it in browser address bar) --> <strong>[" tmppath "]</strong>");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="https://mdbootstrap.com/img/Photos/Others/placeholder-avatar.jpg" id="output" width="100" height="100" style="border-radius: 50%;" />

<input id="myImg" type="file">

I will meet some error as what show in the code snippet like if size too big or not recommended size some error pop out

I get error like "message": "Uncaught TypeError: Failed to execute 'createObjectURL' or "message": "Uncaught TypeError: Failed to execute 'createObjectURL' on 'URL': Overload resolution failed.",

why is this happening ?

how can i fix this issue ?

CodePudding user response:

    var uploadField = document.getElementById("myImg");

    uploadField.onchange = function() {
      // 1000000 = 1MB 
      if (this.files[0].size > 1000000) {
        alert("File is too big!");
        this.value = "";
      } else if (this.files[0].size < 100000) {
        alert("File not recommended size!");
        this.value = "";
      }
    };

    $('#myImg').change(function(event) {
if(event.target.files[0]){
      // var tmppath = URL.createObjectURL(event.target.files[0]);
      $("img#output").fadeIn("fast").attr('src',URL.createObjectURL(event.target.files[0]));
}else{
  alert('Image size mismatched.')
}

      // $("#disp_tmp_path").html("Temporary Path(Copy it and try pasting it in browser address bar) --> <strong>[" tmppath "]</strong>");
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <img src="https://mdbootstrap.com/img/Photos/Others/placeholder-avatar.jpg" id="output" width="100" height="100" style="border-radius: 50%;" />

    <input id="myImg" type="file">

The only thing you need to understand that Jquery will trigger as per changes so make sure to create URL Object once images are available and not unnecessary. Just enlcose your code to if else and it will work. Check the example that has been modified as per.

  • Related