首页 > Web开发 > 详细

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

时间:2017-04-09 18:09:29      阅读:382      评论:0      收藏:0      [点我收藏+]
<!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>

 

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

原文:http://www.cnblogs.com/lovling/p/6685634.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!