Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

TimiAde's avatar

Preserve Image on Refresh

I want to preserve uploaded image on refresh page because as soon as i refresh the page i lose the image. Please how can it be done my html

<input class="@error('image') border-red-600 @else border-gray-300  @enderror block w-full text-sm text-primary-900 bg-gray-50 rounded-lg border cursor-pointer dark:text-gray-400 focus:outline-none dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400" aria-describedby="user_avatar_help" name="image" type="file" accept="image/png, image/gif, image/jpeg, image/jpg" onchange="loadFile(event)">
                        <img id="output" class="mt-6 h-auto w-full md:w-1/2 object-cover rounded-lg"/>

my javascript

var loadFile = function(event) {
            var output = document.getElementById('output');
            output.src = URL.createObjectURL(event.target.files[0]);
            output.onload = function() {
            URL.revokeObjectURL(output.src) // free memory
            }
        };
0 likes
2 replies
LaryAI's avatar
Level 58

To preserve the uploaded image on page refresh, you can make use of the browser's local storage. Here's an example solution using JavaScript:

var loadFile = function(event) {
    var output = document.getElementById('output');
    output.src = URL.createObjectURL(event.target.files[0]);
    output.onload = function() {
        URL.revokeObjectURL(output.src); // free memory
        localStorage.setItem('image', output.src); // store the image URL in local storage
    }
};

// Check if there is a stored image URL in local storage
var storedImage = localStorage.getItem('image');
if (storedImage) {
    var output = document.getElementById('output');
    output.src = storedImage;
}

This solution stores the image URL in the browser's local storage when the image is loaded. On page refresh, it checks if there is a stored image URL in the local storage and sets it as the source of the output element.

Note: Local storage is specific to each browser and device, so the image will only be preserved on the same browser and device where it was uploaded.

TimiAde's avatar

I am having this error

Security Error: Content at http://success-stories.test/blog/create may not load data from blob:http://success-stories.test/2bc2ddca-d2d4-40ed-90f8-bf856c35f928.

@laryai

Please or to participate in this conversation.