美文网首页
jQuery图片上传demo

jQuery图片上传demo

作者: MC桥默 | 来源:发表于2019-11-02 11:35 被阅读0次
前言

项目中往往需要向后台传输图片,有的需要用户自己上传本地,然后提交到后台。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
    </style>
</head>
<body>
    <label for="imgInput">
        <form method="post" name="picForm" id="picForm" >
            <div class="picBox">
                <div class="yourPic">
                    <input type="file" id="imgInput" name="img" class="imgInput" hidden/>
                    <img src="css_sprites.png" alt="" class="myImg" style="width: 50%;height: 500px">
                </div>
            </div>
        </form>
    </label>
<button>提交</button>
</body>
<script>
    $(function () {
        $('#imgInput').change(function(){
            var file = this.files[0];
            if(!/image\/png+/.test(file.type) && !/image\/jpeg+/.test(file.type)){
                alert('只支持png及jpg格式的照片,请重新选择');
                return false;
            }else{
                $('.myImg').attr("src",URL.createObjectURL($(this)[0].files[0]));
            }
        });
        $('button').click(function () {
            var formData = new FormData($( "#picForm" )[0]);
            formData.append("img",$(".myImg").attr('src'));
            $.ajax({
                type: "POST",
                url: "http://xxxxxx",
                data:formData,
                contentType: false,
                processData: false,
                success:function () {},
                error:function () {}
            })
        })
    })
</script>
</html>

相关文章

网友评论

      本文标题:jQuery图片上传demo

      本文链接:https://www.haomeiwen.com/subject/nnpcbctx.html