jq的ajax上传文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jq 文件上传 ajax</title>
    <script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
    <input type="file" name="file">
    <img src="" id="img" width="300" alt="">
    <script>
        $(function(){
            $('input:file').change(function(){
                console.log('123')
                //创建表单对象
                var formD = new FormData()
                //向表单对象添加文件 
                //this当前事件对应的js对象,files是数组
                var that = this
                formD.append('file',this.files[0])//添加名称为file的文件
                $.ajax({
                	//服务器地址
                    url:'https://www.520mg.com/ajax/file.php',
                    type:'POST',//请求方式
                    data:formD,//请求的数据
                    processData:false, //告诉jQuery不要去处理发送的数据
                    contentType:false, //告诉jQuery不要去设置Content-Type请求头
                    success:function(r){//成功处理
                        r = JSON.parse(r).pic //转换json,获取图片地址
                        console.log(r)
                        $('body').append(`<img src="https://www.520mg.com${r}" width='300'>`)//向body内添加图片
                        $(that).val('');//置空this指向的input值(上传文件提示文件名)
                    },
                    error:function(e){ //失败处理
                        console.log(e)
                    }
                })
            })
        })

    </script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/weixin_44348028/article/details/108103357