Search code examples
javascripthtmlcsstwitter-bootstrap

HTML5 - reserving <img> for later use


I am building a website where users can upload a picture, and then it will be displayed. I will need to set this image as their profile picture later on. Here is my code:

<input id="inp" type='file' accept="image/*"onchange="readURL(this);" /><br>
<img id="blah"/>

<script type="text/javascript">
function readURL(input) {
if (input.files && input.files[0]) {
    var reader = new FileReader();

    reader.onload = function (e) {
        $('#blah')
            .attr('src', e.target.result)
            .width(150)
            .height(150);
    };

    reader.readAsDataURL(input.files[0]);
}
}
</script>

Solution

  • I didn't really understand your question, you could save the data in a variable and then use that variable when you have to post the image, you should avoid ever storing images directly in the database, instead store references to them.

    But if you want to simply display the image after selecting it, you can do something like this:

    let input = $('input'),
        img = $('img'),
        reader = new FileReader();
    
    function readFile(e) {
      reader.onload = function(e) {
        img.attr('src', e.target.result)
      }
      
      reader.readAsDataURL(e.target.files[0])
    }
    
    input.on('change', readFile)
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input id="inp" type='file' accept="image/*"/>
    <img/>

    However, if you want to save the image permamently on a database you're gonna have to learn how back-ends work and maybe set up a Restful API.