1

In this snippet onsubmit is used to display the image uploaded and to keep it visible return false; is used.

<form method="POST" enctype="multipart/form-data" onsubmit="display();return false;">
    <input type="file" name="file" id="file">
    <input type="submit" value="Upload">
</form>

JavaScript:

function display() {

    var file = document.getElementById('file').files[0];
    var reader  = new FileReader();
    // it's onload event and you forgot (parameters)
    reader.onload = function(e)  {
        // the result image data
        document.getElementById("img").src = e.target.result;
    }
    // you have to declare the file loading
    reader.readAsDataURL(file);
}

When doing so, the image loads and is displayed but does not upload to the directory of uploads specified.

How can I upload the actual images and show the image without the need of page refresh?

amphetamachine
  • 27,620
  • 12
  • 60
  • 72
iustin
  • 66
  • 10
  • Does this answer your question? [Display selected image from input file](https://stackoverflow.com/questions/57960416/display-selected-image-from-input-file) – amphetamachine Jul 07 '20 at 14:54
  • @amphetamachine it refreshes after submission so not really. but working with the input type="file" worked – iustin Jul 07 '20 at 14:57
  • Oh, so your goal is to keep the uploaded file displayed even after the form submits? – amphetamachine Jul 07 '20 at 15:05
  • yeah, and change it on the next submit. does that require cookies? – iustin Jul 07 '20 at 15:12
  • No, you could store it elsewhere. What happens to the file when you POST the form? If it saves on the server such that it's accessible from a URL, just point the `` at that URL. – amphetamachine Jul 07 '20 at 16:33
  • the image is just saved to an uploads directory, i am not familiar with js so i don't know how pointing the img scr would work. is there a way of joining strings in js so that you make the new img src out of that? – iustin Jul 07 '20 at 16:36

1 Answers1

1

Rather than changing the img after submission or manipulating a submit button I found that it's better to just use this:

<input type="file" name="file" id="file" onchange="preview_image(event)">

And then in js simply read it onchange

function preview_image(event) {
var reader = new FileReader();
reader.onload = function() {
    document.getElementById('img').src = reader.result;
    }
reader.readAsDataURL(event.target.files[0]);
}
iustin
  • 66
  • 10