Skip to main content
The onFileSelected() function handles image file selection from the user’s device, reads the file, and displays it in the browser for classification.

Function signature

function onFileSelected(event)

Parameters

event
Event
required
The file input change event containing the selected file in event.target.files[0]

How it works

The function performs the following steps:
  1. Extracts the selected file from the event object
  2. Creates a FileReader instance to read the file
  3. Sets the image title to the filename
  4. Reads the file as a Data URL
  5. Sets the image source when reading is complete
  6. Handles any errors during the process

Code example

<input type="file" accept="image/*" onchange="onFileSelected(event)">
<img id="image" width="100" height="75"></img>

Implementation

Here’s the complete implementation from the source code:
function onFileSelected(event) {

    try {
        var selectedFile = event.target.files[0];
        var reader = new FileReader();

        imgtag.title = selectedFile.name;

        reader.onload = function(event) {
            imgtag.src = event.target.result;
        };

        reader.readAsDataURL(selectedFile);
    }catch (error){
        alert("Error Reading Image")
    }
    
}

Error handling

The function includes a try-catch block that:
  • Catches any errors during file reading
  • Displays an alert with “Error Reading Image” message
  • Prevents the application from crashing on invalid files
The function assumes the global imgtag variable is initialized. Make sure to define this variable before using onFileSelected().

Required HTML elements

The function requires the following HTML element to be present:
var imgtag = document.getElementById("image")
This element must be defined before the function is called.

File input configuration

For optimal results, configure your file input to accept only image files:
<input type="file" accept="image/*" onchange="onFileSelected(event)">
The accept="image/*" attribute ensures only image files are shown in the file picker.

Image display

The selected image is displayed with dimensions of 100x75 pixels:
<img id="image" width="100" height="75"></img>
After an image is selected and displayed, you can call the predict() function to classify the skin lesion.

Build docs developers (and LLMs) love