前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >bootstrap+jquery实现图片选取后本地预览+增删+表单ajax上传(完整demo)

bootstrap+jquery实现图片选取后本地预览+增删+表单ajax上传(完整demo)

作者头像
超级小可爱
发布2024-04-26 10:16:29
910
发布2024-04-26 10:16:29
举报
文章被收录于专栏:小孟开发笔记小孟开发笔记

本案例是一个投诉内容提交页的代码-功能完整,亲测可行

运行效果截图—支持再次选择和删除不要的图片,图片预览效果的图片数据是本地的,不需要上传就可以预览

代码语言:javascript
复制
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>投诉内容提交</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>

        /* 设置body为flex容器,以使得内容在其内部居中 */
        body {
            display: flex;
            justify-content: center; /* 在水平方向上居中 */
            /*align-items: center; !* 在垂直方向上居中(如果需要的话) *!*/
            height: 100vh; /* 设置body高度为视口高度,确保内容垂直居中 */
            margin: 0; /* 移除body的默认边距 */
        }


        #image-preview {
            display: flex;
            flex-wrap: wrap;
            /*justify-content: space-around;*/
            padding: 10px;
        }



        .image-container {
            position: relative;
            display: inline-block;
            margin: 1px;
        }

        #upload-btn{
            max-width: 80px;
            max-height: 80px;
        }

        .image-container img {
            max-width: 80px;
            max-height: 80px;
            cursor: pointer;
        }
        .delete-button {
            position: absolute;
            top: 0;
            right: 0;
            padding: 3px;
            width: 25px;
            height: 25px;
            background-color: #6F8A91; /* 或者使用图片作为背景 */
            color: white;
            opacity: 0.5; /* 设置透明度为50% */
            border: none;
            cursor: pointer;
            font-size: 16px; /* 根据需要调整字体大小 */
            font-weight: bold;
        }



        .footer{
            text-align: center;
        }
        .btn-primary {
            display: inline-block;
            padding: 6px 12px;
            margin-bottom: 0;
            font-size: 14px;
            font-weight: 400;
            line-height: 1.42857143;
            text-align: center;
            white-space: nowrap;
            vertical-align: middle;
            -ms-touch-action: manipulation;
            touch-action: manipulation;
            cursor: pointer;
            -webkit-user-select: none;
            -moz-user-select: none;
            -ms-user-select: none;
            user-select: none;
            background-image: none;
            border: 1px solid transparent;
            border-radius: 4px;
            color: #fff;
            /*background-color: #337ab7;*/
            border-color: #2e6da4;
        }
    </style>
</head>
<body>

<div class="container mt-4">
    <h1 class="text-center">投诉内容提交</h1>

    <form id="complaint-form" action="#" method="POST" enctype="multipart/form-data">
        <div class="mb-3">
            <label for="content" class="form-label">投诉内容(最多200字)</label>
            <textarea name="content" class="form-control" id="content" rows="3" maxlength="200"></textarea>
        </div>

        <div class="mb-3">
            <label for="evidence-link" class="form-label">证据链接(选填)</label>
            <input name="url" type="text" class="form-control" id="evidence-link" placeholder="请输入证据链接">
        </div>

        <div class="mb-3" id="upload-container">
            <label for="evidence-link" class="form-label">上传图片(最多4张)</label>
            <input name="files" type="file" id="image-upload" accept="image/*" multiple style="display: none;">
            <div id="image-preview">
              <img class="upload" id="upload-btn" src="upload.png" alt="选择图片111"></img>
            </div>
        </div>
        <div class="mb-3 footer">
            <button type="submit" class="btn btn-primary">提交投诉</button>
        </div>


    </form>





</div>

<script>
$(document).ready(function() {


    var selectedFiles = [];// 创建一个数组来存储选中的文件引用
    //图片上传按钮点击事件--触发文件表单隐藏域的上传事件--使用了事件委托技术
    $('#image-preview').on('click', '#upload-btn',function(){
        $('#image-upload').click();
    });

    //本地选择图片+图片预览和删除
    $('#image-upload').on('change', function() {
        var files = this.files;
        $.each(files, function(index, file) {
            var reader = new FileReader();
            reader.onload = function(e) {//这个读取文件的方法是异步的,这里是读取完成后会调用这里的回调
                var img = $('<img>').attr('src', e.target.result);
                img.attr('width','80px');
                img.attr('height','80px');
                var deleteButton = $('<button>').addClass('delete-button').text('X').click(function() {
                    $(this).prev('img').remove();//删除对应的图片
                    $(this).remove();//删除当前图标的图片
                    selectedFiles.splice(index, 1); // 从selectedFiles数组中删除对应的文件引用
                });


                //$('#image-preview').append(img, deleteButton);

                // 将图片和删除按钮包装在一个容器中
                var imageContainer = $('<div>').addClass('image-container').append(img, deleteButton);
                 // 将容器添加到预览区域
                $('#image-preview').append(imageContainer);

                //清除上传按钮,重新插入到最后面
                $('.upload').remove();
                var upload_img='<div class="image-container"><img class="upload" id="upload-btn" src="upload.png" alt="选择图片"></div>';
                $('#image-preview').append(upload_img);
            };
            selectedFiles.push(file);// 将文件引用存储到selectedFiles数组中
            reader.readAsDataURL(file);
            $('.upload').remove();
        });
    });
    //表单ajax调用接口提交数据含图片数据
    $("#complaint-form").submit(function(e) {
        e.preventDefault();// 阻止表单默认的提交行为
        var formData = new FormData(this);
        console.log(selectedFiles);
        $.each(selectedFiles, function(index, file) {
            formData.append('files[]', file); // 假设服务器期望接收一个名为'files'的数组
        });
        $.ajax({
            url: "http://xxxx/api/index/test_form", // 替换为你的API接口地址
            type: "POST",
            data: formData,
            contentType: false, 
            dataType: 'json', // 接受数据的格式--期望返回的数据类型为 JSON
            processData: false,
            success: function(response) {
                alert("投诉已成功提交!");
                // 在成功提交后执行的逻辑,如重定向等
            },
            error: function(xhr, status, error) {
                alert("提交失败:" + error);
            },
        });
    });
});
</script>

</body>
</html>

未经允许不得转载:肥猫博客 ? bootstrap+jquery实现图片选取后本地预览+增删+表单ajax上传(完整demo)

本文参与?腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客?前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与?腾讯云自媒体分享计划? ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
容器服务
腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
http://www.vxiaotou.com