zoukankan      html  css  js  c++  java
  • js 使用 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>
  • 相关阅读:
    Oracle 多表查询优化
    FZU 2150 Fire Game
    HDU 1058 Humble Numbers
    UVA 11624 Fire!
    POJ 1321 棋盘问题
    线性表的基本操作
    POJ 3414 Pots(广搜输出路径)
    HDU 1495 非常可乐
    POJ 1847 Tram
    POJ 3159 Candies(查分约束)
  • 原文地址:https://www.cnblogs.com/lovling/p/6685634.html
Copyright © 2011-2022 走看看