How to preview image before upload in Laravel?

by aniya.jaskolski , in category: PHP Frameworks , 9 months ago

How to preview image before upload in Laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by jerad , 3 months ago

@aniya.jaskolski 

To preview an image before it is uploaded in Laravel, you can use the FileReader API to read the file and display it in the browser.


Here's an example of how you can do this:

  1. In your Laravel blade template, add an input element for file uploads and a img element to display the preview:
1
2
3
4
<form>
  <input type="file" id="image-input" />
  <img src="" id="image-preview" style="display: none;" />
</form>


  1. Add a JavaScript script that uses the FileReader API to read the file and display it in the img element:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
<script>
  const input = document.getElementById('image-input');
  const preview = document.getElementById('image-preview');

  input.addEventListener('change', function() {
    const file = this.files[0];

    if (file) {
      const reader = new FileReader();

      reader.addEventListener('load', function() {
        preview.src = reader.result;
        preview.style.display = 'block';
      });

      reader.readAsDataURL(file);
    } else {
      preview.src = '';
      preview.style.display = 'none';
    }
  });
</script>


This will display a preview of the selected image whenever the file input changes.


Note that this will only work in modern browsers that support the FileReader API. You may want to add a fallback for older browsers that do not support this API.