-1

I'm trying to do a quick client side file check for UX in jscript, but I'm getting an error that I don't know how to fix. I'm getting a file through an input:

I'm getting the following error:

Uncaught TypeError: Cannot read properties of undefined (reading '0')

Every time I searched for how to do this, it gives me the solution I've implemented. When I log file, it returns the file path so maybe that's the issue, that it cannot get the size from the file path alone?

I tried using an approach based on events but I was getting the same error.

const MAXSIZEMB = 100000;

function checkSize() {
  const file = document.getElementById("file").value;
  console.log(file);
  const max = MAXSIZEMB * 1024 * 1024;
  if (file.files[0].size > max) {
    alert("Files size cannot exceed " + MAXSIZEMB + " MB");
    file = "";
  }
}
<input type="file" name="file" id="file" onchange="checkSize()" />
mplungjan
  • 169,008
  • 28
  • 173
  • 236
André Rocha
  • 123
  • 7

1 Answers1

0

You need the file, not file.value

You cannot set the value of a file input for obvious security reasons

You CAN wrap the file input in a form and reset the form

const MAXSIZEMB = 100;
const max = MAXSIZEMB * 1024 * 1024;

function checkSize() {
  const file = document.getElementById("file").files[0];
  console.log(file.size)
  if (file.size > max) {
    alert("Files size cannot exceed " + MAXSIZEMB + " MB");
  }
}
<input type="file" name="file" id="file" onchange="checkSize()" />
mplungjan
  • 169,008
  • 28
  • 173
  • 236