Solution 1 :

Just reference the name property and you’ll have what you’re looking for.

const setFile = () => { 
    console.log(document.getElementById('fileUpload').files[0].name)
}
<input type="file" accept=".docx" type="file" id="fileUpload" onchange="setFile()" />

Other properties such as lastModified, lastModifiedDate, type and others are also available on it so just refer the onces you’ll like to display.

Solution 2 :

“setFile()” treated as string not function call ,So to call SetFile() , You need to Call it , So use onChange={setFile()} , if you are working in react

const setFile = () => { 
    console.log(document.getElementById('fileUpload').files[0].name)
}
<input type="file" accept=".docx" type="file" id="fileUpload" onchange={setFile()} />

Solution 3 :

Your code is indeed extracting the info of the object file. Here you can see been rendered inside <body>

const setFile = () => { 
  const fileObject = document.getElementById('fileUpload').files[0]; 
  document.getElementById('title').style.display = 'block';
  document.getElementById('one').append('Name: ' + fileObject.name)
  document.getElementById('two').append('Last Modified: ' + fileObject.lastModified)
  document.getElementById('three').append('Last Modified Date: ' + fileObject.lastModifiedDate)
  document.getElementById('four').append('Size: ' + fileObject.size)
  document.getElementById('five').append('Type: ' + fileObject.type)
}
div{margin:10px 0}
<input type="file" accept=".docx" type="file" id="fileUpload" onchange="setFile()" />
<h1 id="title" style="display:none">File Info</h1>
<div id="one"></div>
<div id="two"></div>
<div id="three"></div>
<div id="four"></div>
<div id="five"></div>

Solution 4 :

Using a Label tag instead of button tag to trigger the file input helped resolve the issue. Although i can’t understand why.

Problem :

I have this code

Html

<input type="file" accept=".docx" type="file" id="fileUpload" onchange="setFile()" />

Javascript

const setFile = () => { console.log(document.getElementById('fileUpload').files[0])}

And I’m trying to get the selected file to display in the console but to no avail. Pls how can I fix this?

Here is the sandbox link https://codesandbox.io/embed/fancy-river-9dn69?codemirror=1

Comments

Comment posted by Ran Turner

what do you want to be displayed? is it the name?

Comment posted by henrie

The file name and its other properties

Comment posted by Gass

Your code is displaying information on the console.

Comment posted by henrie

@Gass it doesn’t display

Comment posted by henrie

Unfortunately I’m getting same outcome. Nothing is being displayed in the console

Comment posted by henrie

Its just html and javascript

Comment posted by henrie

Still not displaying

By