This JavaScript code snippet demonstrates how to handle different file types when a user selects a file. It’s useful when you need to perform different operations based on the file type selected by the user.
Code Snippet
<input id="fileInput" type="file">
<script>
const fileInput = document.getElementById('fileInput');
fileInput.addEventListener('change', function(e) {
const fileName = this.files[0].name;
const fileExt = fileName.split('.').pop();
switch (fileExt) {
case 'png':
// handle .png files
break;
case 'jpg':
// handle .jpg files
break;
case 'pdf':
// handle .pdf files
break;
default:
// handle any other file that doesn't match the cases above
break;
}
})
</script>
Explanation
In this snippet, an event listener is added to the file input field to listen for the change
event. This event is triggered when a user selects a file.
The event handler function retrieves the file name from the first file in the files
array (this.files[0].name)
, splits it by the ‘.’ character using the split()
method, and then gets the last part of the split string using the pop()
method.
This last part is typically the file extension. A switch
statement is then used to check the file extension and perform different operations based on the file type.
You can then use a switch statement to check the file extension and determine what operation to perform.
Usage
This code can be used in any JavaScript or web development project where there’s a need to handle different file types.
To use it, embed the provided code into your HTML file and replace the comments in the switch
statement with the actual code to handle the respective file types.
Example
For instance, in a scenario where multiple files of different types are uploaded, this script can be used to determine if the file should be sent to an image handler function, a PDF handler function, or some other function for different file types.
Conclusion
Identifying and handling different file types is a common task in web development, especially when dealing with file uploads.
This JavaScript code snippet provides a simple and effective way to determine the file type and perform different operations based on it.
It’s easily adaptable to fit the needs of various web development projects.