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>
  • 相关阅读:
    机器学习-初学者入门
    安装.cer证书并将证书从.cer格式转化为.pem格式
    字符串反转C#的实现
    Linux系统下远程文件拷贝scp命令
    【Django】ESRTful APi
    数据结构-栈跟队列基础部分
    数据结构-排序
    数据分析--Matplotlib的基本使用
    数据分析--pandas的基本使用
    数据分析--numpy的基本使用
  • 原文地址:https://www.cnblogs.com/lovling/p/6685634.html
Copyright © 2011-2022 走看看