create a file preview in javascript

To create a file preview in JavaScript, you can follow the below steps:

  1. First, create an HTML form for file upload. Here's an example:
<form>
  <input type="file" id="fileInput">
</form>
52 chars
4 lines
  1. Next, add an event listener to the file input element to listen for when a user selects a file:
index.tsx
const fileInput = document.getElementById('fileInput');

fileInput.addEventListener('change', (event) => {
  const file = event.target.files[0];
  // do something with the file
});
181 chars
7 lines
  1. Use the FileReader API to read the contents of the file and create a preview. Here's how you can create a preview for an image file:
index.tsx
const fileInput = document.getElementById('fileInput');
const previewContainer = document.getElementById('previewContainer');
const previewImage = previewContainer.querySelector('.preview-image');

fileInput.addEventListener('change', (event) => {
  const file = event.target.files[0];
  const reader = new FileReader();

  reader.addEventListener('load', () => {
    previewImage.setAttribute('src', reader.result);
  });

  reader.readAsDataURL(file);
});
458 chars
15 lines
  1. Finally, you can style the preview container using CSS to ensure that it looks the way you want. Here's an example:
.preview-container {
  width: 50%;
  margin: 0 auto;
  text-align: center;
}

.preview-image {
  max-width: 100%;
  max-height: 300px;
  margin-top: 20px;
}
157 chars
12 lines

gistlibby LogSnag