微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – HTML文件上传 – 为什么要使用IFrame

我一直试图让文件上传在IE8中运行.我只看到解决方案是发布到IFrame.为什么这样做?不可能有一个简单的表格,例如

<form action="test.PHP" method="post" enctype="multipart/form-data">
    Select image to upload:
    <input type="file" name="filetoUpload" id="filetoUpload">
    <input type="submit" value="Upload Image" name="submit">
</form>

哪个直接提交给PHP
    

if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["filetoUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}

为什么需要IFrame?

谢谢

解决方法:

iframe方法非常简单.
基本上你使用iframe上传文件而不是上传主窗口,但你不需要使用iframe.

方法1

这是一个关于这个主题的好教程:http://hungred.com/how-to/tutorial-easiest-asynchronous-upload-file-ajax-upload/

HTML:

<form id="my_form" name="form" action="upload.PHP" method="POST" 
enctype="multipart/form-data" >

<div id="main">
<input name="my_files" id="my_file" size="27" type="file" />
<input type="button" name="action" value="Upload" onclick="redirect()"/>
<iframe id='my_iframe' name='my_iframe' src="">
</iframe>
</div>    
</form>

JS:

function redirect()
{
//'my_iframe' is the name of the iframe
document.getElementById('my_form').target = 'my_iframe';
document.getElementById('my_form').submit();
}

PHP

$uploaddir = '/images/';
$uploadfile = $uploaddir . basename($_FILES['my_files']['name']);

if (move_uploaded_file($_FILES['my_files']['my_name'], $uploadfile)) {
echo "success";
} else {
echo "error";
}

2. AJAX方法

JS:

function submitForm() {
        var formData = new FormData($('#imageForum')[0]);

            $.ajax({
                url: '/FileUpload',
                type: 'POST',
                data: formData,
                async: false,
                success: function (data) {
                    alert('posted')
                },
                cache: false,
                contentType: false,
                processData: false
            });

            return false;
    }

HTML:

<form id="imageForum" action="javascript:submitForm();" method="post" enctype = "multipart/form-data">
    <div>
        <label for="fileUpload">File upload</label>
        <input type="file" id="fileUpload" name="fileUpload" />
    </div>
</form>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐