iframe模拟Ajax上传文件

xmlhttprequest level 1中,Ajax是不能够上传文件的,因为js不能操作本地文件,但是市场上有一些Ajax异步上传文件的插件,是怎么完成的呢?答案:可以使用iframe模拟Ajax上传文件。接下来博主将使用iframe来模拟Ajax来上传文件。

首先看一下效果图:
这里写图片描述

文件结构图:
这里写图片描述

09-iframe-upload.html文件:
页面中有一个表单,表单中有一个上传文件按钮和提交按钮,点击提交按钮执行ajaxUpload函数,然后动态创建iframe标签,让其不可见,最后设置表单的target属性指向iframe。

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>iframe模拟Ajax上传文件</title>
    <link rel="stylesheet" href="">
</head>
<script src="http://libs.baidu.com/jquery/1.7.2/jquery.min.js"></script>
<script>
    /**
     * 文件上传
     * @return bool 是否提交表单
     * 1、捕捉表单提交的动作
     * 2、动态创建iframe标签,然其不可见
     * 3、设置表单的target属性指向iframe
     */
    function ajaxUpload(){
        var iframeName = 'upload'+Math.random();//给iframe取名
        $('<iframe name='+iframeName+' width="0" height="0" frameborder="0"></iframe>').appendTo($('body'));//动态创建iframe
        $('form:first').attr('target',iframeName);//设置form的target属性
        $('#progress').html('<img src="progress.jpg"/>');//显示上传是否成功
        //return false;
    }
</script>
<body>
    <h1>iframe模拟Ajax上传文件</h1>
    <h2 id="progress"></h2>
    <form action="09-iframe-upload.php" method="post" enctype="multipart/form-data" onsubmit="return ajaxUpload();">
        <p><input type="file" name="pic"/></p>
        <p><input type="submit" value="提交" /></p>
    </form>
</body>
</html>

09-iframe-upload.php文件:
首先延时3秒,为了能看到加载的图片,然后判断是否有上传文件,然后返回一段Js代码,这段js是在页面中显示是否上传成功

<?php
/**
 * iframe模拟Ajax上传文件
 * @author webbc
 */
sleep(3);//延时3秒
if(empty($_FILES)){
    echo 'no file';
}
$error = $_FILES['pic']['error'] == 0?'succ':'fail';//判断上传是否成功
echo "<script>parent.document.getElementById('progress').innerHTML='$error'</script>";//显示上传是否成功
?>
原文地址:https://www.cnblogs.com/cnsec/p/13407059.html