gpt4 book ai didi

javascript - 是否可以仅通过 jQuery 将一张图像替换为用户即时选择的另一张图像?

转载 作者:行者123 更新时间:2023-11-28 13:25:35 24 4
gpt4 key购买 nike

我让用户选择一张图像,并且我想更改即时显示的图像,而不必依赖 PHP 等服务器端脚本?

基本上,我有一个包含以下内容的 HTML:

<input type="file" id="file" name="file" />
<img id="imagedisplay" src="http://path/to/some/image.jpg" />

然后在 jQuery 方面我有以下内容:

$('#file').change(function(e){
alert($(this).val());
});

我希望将imagedisplaysrc替换为用户选择的本地引用到其系统的$(this).val() 仅显示文件名,因此我无法将其作为源引用。

最佳答案

您可以使用FileReader API。

The FileReader object lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer.

其方法FileReader.readAsDataURL()

The readAsDataURL method is used to read the contents of the specified Blob or File.

注意:它适用于现代浏览器

$(document).ready(function() {

$('#file').change(function(e) {

var reader = new FileReader();
reader.onload = function(e) {
$('#imagedisplay').attr('src', e.target.result);
}
reader.readAsDataURL(this.files[0]);

});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="file" name="file" />
<img id="imagedisplay" src="" />

关于javascript - 是否可以仅通过 jQuery 将一张图像替换为用户即时选择的另一张图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29509272/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com