JavaScript OnChange file input

Quang Nguyen
quangtn0018
Published in
2 min readSep 3, 2018

Last month, I was working on a project that involved file/image uploading and I thought I would share what I have learned to those of you who are looking to do the same in JavaScript.

I created a post on how to Send data and file input through multi-part forms with FormData in HTML if you guys wanted to know and are wondering how it works. It is kind of a prerequisite knowledge for this post, but not absolutely necessary.

// onChange.html<form id="fileUploadForm" enctype="multipart/form-data">
<label for="imageUpload" class="uploadBox">
<p id="uploadMsg">Filename will appear here after file has been selected</p>
<input id="imageUpload" class="imageUploadInput" type="file" name="image" accept="image/*">
</label>
</form>
// onChange.css.uploadBox {
position: absolute;
background: lightblue;
width: 300px;
height: 200px;
}
.imageUploadInput {
display: none;
}

To start off, we will create a simple form element in HTML with the enctypeto send file/image data. I styled this file upload so that you can click to select a file as long as you click inside the lightblue box. I also hid the input because it is not that nice, hence the display: none .

// onChange.jslet imageUpload = document.getElementById("imageUpload");
let uploadMsg = document.getElementById("uploadMsg");
// display file name if file has been selected
imageUpload.onchange = function() {
let input = this.files[0];
let text;
if (input) {
//process input
text = imageUpload.value.replace("C: \\fakepath\\", "");
} else {
text = “Please select a file”;
}
uploadMsg.innerHTML = text;
};

For this JavaScript file, we get the input and upload message by its ID. Then whenever you select a file, the uploadMsg text will change to the name of the file you have selected. Getting the text from the onChange function like this will give you a “C:\\fakepath\\” at the beginning of the file name. To remove this, I replaced “C:\\fakepath\\” with an empty string to display our uploadMsg correctly.

By default, the file input type will display the name of the file, but remember that I have display: none on the input box, so the default input file name will not be displayed.

And that’s how you implement onChange for file inputs! You guys should use this code and play around with it if you would like.

--

--