how to display uploaded image in html using javascript

How to Display Uploaded Image in HTML Using JavaScript

If you have ever built a website or a web application that requires image uploading, you might have wondered about how to display the uploaded image on the page. There are several ways to do this, but one of the most common is using JavaScript.

Method 1: Using a File Input Element and JavaScript

The first method involves creating a file input element using HTML and then using JavaScript to read the file and display it on the page. Here's how you can do it:

  1. Create an HTML file input element:
<input type="file" id="fileInput">
  1. Add an event listener to the input element:
const fileInput = document.getElementById('fileInput');
fileInput.addEventListener('change', (event) => {
  const file = event.target.files[0];
  // do something with the file
});
  1. Read the file using the FileReader API:
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = (event) => {
  const imageUrl = event.target.result;
  // display the image on the page
};
  1. Create an image element and set its source to the URL of the uploaded image:
const image = document.createElement('img');
image.src = imageUrl;
document.body.appendChild(image);

Method 2: Using FormData and AJAX

The second method involves using FormData to send the uploaded file to the server via AJAX and then receiving the URL of the uploaded image and displaying it on the page. Here's how you can do it:

  1. Create a FormData object:
const formData = new FormData();
formData.append('file', file);
  1. Send the FormData object to the server via AJAX:
const xhr = new XMLHttpRequest();
xhr.open('POST', '/upload');
xhr.send(formData);
xhr.onload = () => {
  const imageUrl = xhr.responseText;
  // display the image on the page
};
  1. Create an image element and set its source to the URL of the uploaded image:
const image = document.createElement('img');
image.src = imageUrl;
document.body.appendChild(image);

Both methods have their advantages and disadvantages, and the choice depends on your specific use case. However, they both use JavaScript to display the uploaded image on the page, making it a versatile and useful tool for web developers.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe