SoFunction
Updated on 2025-04-10

Simple example of uploading file previews for js

1. FILE API

html5 provides two methods: FIle and FileReader, which can read file information and read files.

2. example

<html>
<body>
<div  
style="border: 1px solid rgb(204, 204, 204); width: 100%; height: 200px; background-size: contain; background-repeat: no-repeat; background-position: center center;"> </div>
<br/>
<div ></div>
<br/>
<input type="file" >
<script type="text/javascript">

var
  fileInput = ('test-image-file'),
  info = ('test-file-info'),
  preview = ('test-image-preview');
// Listen to change events:('change', function () {
  // Clear background image:   = '';
  // Check whether the file is selected:  if (!) {
     = 'No file selected';
    return;
  }
  // Get File reference:  var file = [0];
  // Get File information:   = 'document: ' +  + '<br>' +
           'Size: ' +  + '<br>' +
           'Revise: ' + ;
  if ( !== 'image/jpeg' &&  !== 'image/png' &&  !== 'image/gif') {
    alert('Not a valid picture file!');
    return;
  }
  // Read the file:  var reader = new FileReader();
   = function(e) {
    var
      data = ; // 'data:image/jpeg;base64,/9j/4AAQSk...(base64 encoding)...'     = 'url(' + data + ')';
  };
  // Read the file in the form of DataURL:  (file);
});
</script>

</body>
</html>

The file read in the form of DataURL is a string, similar to data:image/jpeg;base64,/9j/4AAQSk...(base64 encoding)...

Commonly used to set up images. If the server-side processing is required, send the string base64 and the following characters to the server and decode it with Base64 to get the binary content of the original file.

3. Explanation

The above code also demonstrates an important feature of JavaScript, which is the single-thread execution mode. In JavaScript, the browser's JavaScript execution engine always executes in single-threaded mode when executing JavaScript code, which means that at any time, it is impossible for the JavaScript code to have more than 1 thread being executed at the same time.

You might ask, how to handle multitasking in single-threaded mode?

In JavaScript, multitasking is actually asynchronously called, such as the above code:

(file);

An asynchronous operation will be initiated to read the file contents. Because it is an asynchronous operation, we don't know when the operation ends in JavaScript code, so we need to set a callback function first:

 = function(e) {
  // When the file is read, this function is automatically called:};

When the file read is completed, the JavaScript engine will automatically call the callback function we set. When the callback function is executed, the file has been read, so we can safely obtain the file contents inside the callback function.

The above simple example of preview of the js upload file is all the content I share with you. I hope you can give you a reference and I hope you can support me more.