Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

View image selected from file-system on client-side before upload?

I have an input tag on a form for selecting images to upload.

<div id="lowresDemo">
    <img src="some-url" />
</div>
<input type="file" id="FileToUpload" name="FileToUpload" />

I've attempted to change the a thumbnail displayed on the form next to the input to affirm to the user that their selection was the intended with the following jquery code:

$('#FileToUpload').change(function () {
    $('#lowresDemo img').attr('src', $(this).val());
});

...this doesn't work in any browser, for browser security reasons I beleieve (as I remember from the last time I did something like this years ago).

QUESTION:
Is there a way to present the user's choice of image before they submit the form -- and not just the filepath+name of the value in the input field, but a thumbnail showing the file they've selected?

Or does modern browser security prevent this?

like image 856
Faust Avatar asked Jun 06 '11 10:06

Faust


People also ask

How do I preview an image before uploading HTML?

html. We have two main elements that we will interact with using JavaScript. First, we have a division element that contains the “img” tag. Using Jquery, we will change the “src” attribute of the “img” tag on upload to preview the image.


2 Answers

It's possible with the File API (IE does not support the File API)

<input type="file">
<script type="text/javascript">
    $(document).ready(function() {
    $("input").change(function(e) {

    for (var i = 0; i < e.originalEvent.srcElement.files.length; i++) {
        var file = e.originalEvent.srcElement.files[i];

        var img = document.createElement("img");
        var reader = new FileReader();
        reader.onloadend = function() {
            img.src = reader.result;
        }
        reader.readAsDataURL(file);
        $("input").after(img);
    }
});
    });
</script>

Working example: http://jsfiddle.net/ugPDx/

like image 106
Peeter Avatar answered Oct 03 '22 00:10

Peeter


There is no way to perform the operation before uploading the picture.

But think of it in a different way - the user "doesn' care" if the picture is already uploaded - you could show the thumbnail after they've uploaded, and show a confirm checkbox. Gmail does this with their email attachments - as soon as you selected the file to attach, the upload starts. But the user always has the option to uncheck the file, and it won't be included in the email.

like image 40
Chii Avatar answered Oct 03 '22 00:10

Chii