Subir imagen usando JavaScript

  1. Cargar imagen de JavaScript
  2. JavaScript Cargar imagen sin ancho o alto definido
Subir imagen usando JavaScript

Un usuario puede cargar una imagen a partir de un archivo HTML creando un campo de entrada del tipo de archivo en la sección del cuerpo. En este artículo, mostraremos ejemplos de cómo cargar una imagen usando JavaScript.

ADVERTISEMENT

Cargar imagen de JavaScript

Se usará una etiqueta div con una identificación de display_image para mostrar la imagen que se cargará como salida con ancho y alto definidos.

Sintaxis:

HTML
 htmlCopy<input type ="file" id ="image_input" accept ="image/jpeg, image/png, image/jpg">
<div id="display_image"></div>

Para garantizar que la imagen cargada encaje perfectamente en el interior, las propiedades de la imagen deben agregarse a un archivo CSS con los valores adecuados. Aquí, el borde no es una propiedad esencial que deba agregarse, pero hará que el usuario vea fácilmente dónde aparece la imagen.

CSS
 cssCopy#display-image{
width: 500px;
height: 325px;
border: 2px solid black;
background-position: center;
background-size: cover;
}

A continuación, se debe crear un archivo JavaScript para obtener acceso al campo de entrada y adjuntar un detector de eventos "cambio", que es un evento que se ejecuta cuando el usuario ha cambiado el valor de un elemento. Bajo este detector, un usuario debe obtener acceso al objeto FileReader que permitirá que las aplicaciones web lean el contenido de los archivos o búferes de datos sin procesar almacenados en la máquina local del usuario y adjunte un detector de eventos "load" cuando toda la página está completamente cargada, incluidas todas las fuentes dependientes, como imágenes, archivos CSS y archivos JavaScript.

En pocas palabras, la imagen cargada se traduce a un formato visualizable. La imagen cargada se almacenará en la variable uploadImage, y esta variable se utilizará para inicializar la propiedad backgroundImage en CSS.

JavaScript
 javascriptCopyconst image_input = document.querySelector('#image_input');

image_input.addEventListener('change', function() {
  const file_reader = new FileReader();
  file_reader.addEventListener('load', () => {
    const uploaded_image = file_reader.result;
    document.querySelector('#display_image').style.backgroundImage =
        `url(${uploaded_image})`;
  });
  file_reader.readAsDataURL(this.files[0]);
});

Código fuente completo:

HTML
 htmlCopy<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript Upload Image </title>
<style>
#display_image{
  width: 500px;
  height: 325px;
  border: 2px solid black;
  background-position: center;
  background-size: cover;
}
</style>
</head>

<body>

  <input type="file" id="image_input" accept="image/jpeg, image/png, image/jpg">
  <div id="display_image"></div>

<script>
const image_input = document.querySelector("#image_input");

image_input.addEventListener("change", function() {
  const file_reader = new FileReader();
  file_reader.addEventListener("load", () => {
    const uploaded_image = file_reader.result;
    document.querySelector("#display_image").style.backgroundImage = `url(${uploaded_image})`;
  });
  file_reader.readAsDataURL(this.files[0]);
});
</script>
</body>
</html>

Producción:

cargar imagen usando javascript con ancho y alto definidos

JavaScript Cargar imagen sin ancho o alto definido

También podemos subir una imagen sin ancho ni alto definido en su tamaño original en JavaScript. Siga los pasos a continuación.

Código fuente completo:

HTML
 htmlCopy<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>JavaScript Upload Image</title>
</head>
<body>
    <input type="file" id="file" onchange="FileValidation(event)" >
    <br><br><br>
    <h2>Uploaded Image by the User</h2>
    <img id="uploaded image">
</body>
<script>
    FileValidation = (event) => {
        var uploaded_image = document.getElementById('uploaded image');
    uploaded_image.src = URL.createObjectURL(event.target.files[0]);
        const selected_file = document.getElementById("file");
        if (selected_file.files.length > 0) {
            for (const i = 0; i <= selected_file.files.length - 1; i++) {
                const file_size = selected_file.files.item(i).size;

                const file = Math.round((file_size / 1024));
                }
                }
                }
</script>
</html>

Producción:

cargar imagen usando javascript sin ancho y alto definidos

A partir del código anterior, el usuario puede seleccionar y cargar cualquier tipo de archivo, pero no se puede mostrar. Con implementaciones adicionales, se pueden realizar múltiples cargas de imágenes agregando más codificación a los programas anteriores según el requisito.

¿Disfrutas de nuestros tutoriales? Suscríbete a DelftStack en YouTube para apoyarnos en la creación de más guías en vídeo de alta calidad. Suscríbete
Migel Hewage Nimesha avatar Migel Hewage Nimesha avatar

Nimesha is a Full-stack Software Engineer for more than five years, he loves technology, as technology has the power to solve our many problems within just a minute. He have been contributing to various projects over the last 5+ years and working with almost all the so-called 03 tiers(DB, M-Tier, and Client). Recently, he has started working with DevOps technologies such as Azure administration, Kubernetes, Terraform automation, and Bash scripting as well.

Artículo relacionado - JavaScript Upload