Javascript 在上传之前查看从客户端文件系统中选择的图像?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6250704/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:56:58  来源:igfitidea点击:

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

javascriptjqueryhtmlforms

提问by Faust

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:

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

$('#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?

或者现代浏览器安全是否阻止了这种情况?

回答by Peeter

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

文件 API 是可能的(IE 不支持文件 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/

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

回答by Chii

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.

但是换一种方式想一想——用户“不关心”图片是否已经上传——你可以在他们上传后显示缩略图,并显示一个确认复选框。Gmail 使用他们的电子邮件附件执行此操作 - 一旦您选择了要附加的文件,就会开始上传。但是用户始终可以选择取消选中该文件,并且它不会包含在电子邮件中。