任程
程序
Ajax 与 jQuery 晾序设计(书籍)

jquery 碰患怎誊漆汛 FileReader 实现图片上传秽览效果?

关注者
2
被浏览
1,964

3 个回答

代码如银:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Image Upload Preview</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <input type="file" id="imageUpload">
    <img id="imagePreview" src="#" alt="Image Preview" style="display:none; max-width: 300px; max-height: 300px;">

    <script>
        $(document).ready(function() {
            $("#imageUpload").on("change", function() {
                let input = this;
                if (input.files && input.files[0]) {
                    let reader = new FileReader();
                    reader.onload = function(e) {
                        $('#imagePreview').attr('src', e.target.result).show();
                    };
                    reader.readAsDataURL(input.files[0]);
                }
            });
        });
    </script>
</body>
</html>

发布于 2023-03-31 08:49