• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
山高我为峰
博客园    首页    新随笔    联系   管理    订阅  订阅
原生JS和jQuery版实现文件上传功能
<!doctype html>
<html lang="zh">
<head>
    <meta charset="utf-8">
    <title>HTML5 Ajax Uploader</title>
    <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>

<body>
<p><input type="file" id="upfile" name="file"></p>
<p><input type="button" id="upJS" value="用原生JS上传"></p>
<p><input type="button" id="upJQuery" value="用jQuery上传"></p>
<script>
    /*原生JS版*/
    document.getElementById("upJS").onclick = function () {
        /* FormData 是表单数据类 */
        var fd = new FormData();
        var ajax = new XMLHttpRequest();
        fd.append("otherParam", 1);
        /* 把文件添加到表单里 */
        fd.append("file", document.getElementById("upfile").files[0]);
        ajax.open("post", "/cyberspace/vrv/files", true);

        ajax.onload = function () {
            console.log(ajax.responseText);
        };

        ajax.send(fd);

    }

    /* jQuery 版 */
    $('#upJQuery').on('click', function () {
        var fd = new FormData();
        fd.append("otherParam", 1);
        fd.append("file", $("#upfile").get(0).files[0]);
        $.ajax({
            url: "/cyberspace/vrv/files",
            type: "POST",
            processData: false,
            contentType: false,
            data: fd,
            success: function (d) {
                console.log(d);
            }
        });
    });
</script>
</body>
</html>

注:http://www.jb51.net/article/82611.htm

posted on 2018-03-05 14:39  山高我为峰  阅读(1392)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3