上传前在客户端查看从文件系统中选择的图像? [英] View image selected from file-system on client-side before upload?

查看:165
本文介绍了上传前在客户端查看从文件系统中选择的图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 < div id =lowresDemo>< p> ; 
< img src =some-url/>
< / div>
< input type =fileid =FileToUploadname =FileToUpload/>

我试图更改输入旁边表单上显示的缩略图以确认用户,他们的选择是与以下jQuery代码的意图:

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

...这不适用于任何浏览器,为了浏览器的安全性,记得从上次我做了像这样的几年前)。



问题

有没有办法在提交表单之前呈现用户对图像的选择 - 而不仅仅是输入字段中的文件路径+值的名称,而是显示他们选择的文件的缩略图?



或者现代浏览器安全性是否可以防止这种情况发生?

解决方案

使用File API(IE不支持File API)

 < input type =file> 
< script type =text / javascript> (变量i = 0; i< b)变量(函数(e){

) ; 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>

工作示例: http://jsfiddle.net/ugPDx/


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?

解决方案

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/

这篇关于上传前在客户端查看从文件系统中选择的图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆