Creé un marcador de posición con una imagen que puede cargar el archivo, luego creo una condición para que el tamaño del archivo recomendado sea de 100 kb o más y menos de 1 mb de tamaño de carga
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">Me encontraré con algún error como el que se muestra en el fragmento de código, como si el tamaño es demasiado grande o el tamaño no recomendado aparece algún error
Recibo un error como "mensaje": "TypeError no detectado: no se pudo ejecutar 'createObjectURL' o "mensaje": "TypeError no detectado: no se pudo ejecutar 'createObjectURL' en 'URL': la resolución de sobrecarga falló".,
Por qué está pasando esto ?
¿Cómo puedo solucionar este problema?
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">Lo único que debe comprender es que Jquery se activará según los cambios, así que asegúrese de crear un objeto de URL una vez que las imágenes estén disponibles y no sean innecesarias. Simplemente incluya su código en if else y funcionará. Compruebe el ejemplo que se ha modificado según.