Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
254 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...