Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
238 views
Welcome To Ask or Share your Answers For Others

1 Answer

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...