0

I have an image upload box. Standard stuff:

<input id="image-upload-input" type="file" />

Once the user picks a file, I can access the contents and send it to my API over Axios like such:

const imageUploadInput = document.getElementById("image-upload-input");
const file = imageUploadInput.files[0];
if (!file) {
  return;
}

const reader = new FileReader();
const component = this;

reader.onload = function (event) {
  axios.post("upload/image", Buffer.from(event.target.result));
};
reader.readAsArrayBuffer(file);

However, I have some restrictions regarding dimensions and would like to check those on the client side.

I am fairly certain it can be done. I haven't tried it yet but I imagine if I just pop the data into an (ideally invisible) img tag with a data src attribute, that might work. Does anyone have any working code? Or a better way to do it?

kaan_a
  • 3,503
  • 1
  • 28
  • 52

1 Answers1

2

adding something like this should work

imageUploadInput.onchange = function (event) {
  const file = imageUploadInput.files[0];
  if (!file) {
    return;
  }
  const image = new Image();
  image.onload = function() {
    console.log(this.width, this.height);
  }
  image.src = URL.createObjectURL(file);
};
dhudson
  • 571
  • 3
  • 9