Skip to content

Instantly share code, notes, and snippets.

@huggler
Created March 29, 2021 14:14
Show Gist options
  • Save huggler/4fd954bfd32bed882addaaa689cee485 to your computer and use it in GitHub Desktop.
Save huggler/4fd954bfd32bed882addaaa689cee485 to your computer and use it in GitHub Desktop.
Componente de upload de foto que redimensiona antes de enviar para o servidor e devolve a base64
const handleUploadImage = async (e) => {
var images = Array.from(e.target.files);
var _files = form.files;
images.forEach(async (item) => {
var maxW=500;
var maxH=500;
var _img = new Image();
_img.onload = () => {
var id = new Date().getTime();
var canvas = document.createElement("canvas");
canvas.setAttribute("id", `${item.name}-${id}`);
document.getElementById("conteudo").appendChild(canvas)
var ctx = canvas.getContext("2d");
console.log('canvas => ', canvas);
var iw=_img.width;
var ih=_img.height;
var scale=Math.min((maxW/iw),(maxH/ih));
var iwScaled=iw*scale;
var ihScaled=ih*scale;
canvas.width=iwScaled;
canvas.height=ihScaled;
ctx.drawImage(_img,0,0,iwScaled,ihScaled);
var base64 = canvas.toDataURL();
document.getElementById("conteudo").removeChild(canvas);
_files.push({typeMedia: 'image', filename: base64})
setForm({...form, files: _files});
document.getElementById('file').value = null;
}
_img.src = URL.createObjectURL(item);
})
}
<div className="col-md-12">
<div className="form-group">
<label htmlFor="file" className="btn btn-outline-primary btn-block rounded-pill m-0">
<input
onChange={handleUploadImage}
name="file"
id="file"
multiple
type="file"
className="upload d-none"
/>
<PhotoLibraryIcon /> selecionar as fotos
</label>
<p className="text-center">{form.files.length} fotos selecionadas</p>
</div>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment