HTML5 ( 借助http请求发送formdata对象,从而上传文件 ) XMLHttpRequest, FormData

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>JS文件上传</title>
    <script type="text/javascript" src="../js/jQuery.js"></script>
    <style type="text/css">
        * {
            margin: 0;
            padding: 0;
        }
        
        #img {
            display: block;
            width: 9.98rem;
            height: 6rem;
            border: .01rem solid black;
        }
        
        #file {
            display: block;
            margin: -6rem 0 0 0;
            opacity: 0;
            width: 10rem;
            height: 6rem;
        }
        
        #submit {
            display: block;
            width: 5rem;
            height: 2rem;
            margin: .5rem 2.5rem;
            font-size: .45rem;
            text-align: center;
            line-height: 2rem;
        }
    </style>
</head>
<body>
    <img id="img" src="" />
    <input id="file" type="file" />
    <input id="submit" type="button" value="提交文件" />
</body>
</html>
<script type="text/javascript">
    // rem布局
    $('html').css('font-size', $(window).width() / 10);
    // 实例化formData对象
    var formData = new FormData();
    // 当选取文件时
    $('#file').on("change", function() {
        var fileList = $("#file")[0].files;
        var src = URL.createObjectURL(fileList[0]);
        $('#img').attr('src', src);
        formData.append("file", fileList[0]);
    });
    // 点击提交上传时
    $("#submit").on('click', function(){
        /**
         * http 请求对象 XMLHttpRequest
         * XMLHttpRequest.open(请求方式, 请求地址, 是否异步 )
         * XMLHttpRequest.onload: 请求响应时调用的方法
         * e.target.responseText: 服务器响应的文本内容 
         */
        var httpRequest = new XMLHttpRequest();
        httpRequest.open("POST", "http://192.168.0.105/WebTest/FileUploadServlet", true);
        httpRequest.onload = function(e){
            console.log(e.target.responseText);
        }
        httpRequest.send(formData);
    });
</script>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值