Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

221
Views
Reemplazar la imagen en "<input>" por una nueva con el tamaño reducido

En primer lugar, JS no es mi idioma habitual, disculpe si la pregunta no es muy clara.

He estado probando un codigo para comprimir las imagenes que suben los usuarios a un <input> el codigo JS de compresion esta funcionando perfectamente pero no se como hacer para reemplazar el archivo que han elegido en el "input" por el uno que acabo de generar comprimido.

Quiero hacer esto porque <input> está dentro de un formulario para poder subir la imagen comprimida al servidor.

Aquí está la compresión JS fot:

 const MAX_WIDTH = 300; const MAX_HEIGHT = 200; const MIME_TYPE = "image/jpeg"; const QUALITY = 0.8; const input = document.getElementById("img-1"); input.onchange = function (ev) { const file = ev.target.files[0]; // get the file const blobURL = URL.createObjectURL(file); const img = new Image(); img.src = blobURL; img.onerror = function () { URL.revokeObjectURL(this.src); // Handle the failure properly console.log("Cannot load image"); }; img.onload = function () { URL.revokeObjectURL(this.src); const [newWidth, newHeight] = calculateSize(img, MAX_WIDTH, MAX_HEIGHT); const canvas = document.createElement("canvas"); canvas.width = newWidth; canvas.height = newHeight; const ctx = canvas.getContext("2d"); ctx.drawImage(img, 0, 0, newWidth, newHeight); canvas.toBlob( blob => { // Do something with img in my case show in Frontend displayInfo('Original file', file); displayInfo('Compressed file', blob); }, MIME_TYPE, QUALITY); // Only for testing and see results document.getElementById("pruebas-tam").append(canvas); }; };
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Después de muchas pruebas logré encontrar la solución, agregando estas líneas justo donde tenemos el 'blob' podemos reemplazar la entrada con la nueva imagen comprimida. La solución se basa en crear un archivo usando el Blob y luego asignarlo a un DataTransfer y finalmente asignarlo nuevamente a la Entrada.

 displayInfo('Original file', file); displayInfo('Compressed file', blob); // Here is where we convert the blob into a file and put inside DataTransfer let newfile = new File([blob], "filename.ext",{type:MIME_TYPE, lastModified:new Date().getTime()}); let container = new DataTransfer(); container.items.add(newfile); input.files = container.files;
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!