XMLHttpRequest上传进度是不可计算的

时间:2016-08-26 00:06:31

标签: javascript xmlhttprequest async-onprogressupdate

我正在尝试使用XMLHttpRequest上传文件,但我无法获得进度回调(下面的req.upload.onprogress)才能正常工作。它总是报告evt.lengthComputable为false。但是,服务器php正确报告文件属性(请参阅下面的log.txt列表),并且文件已正确保存到files目录。

回调不知道内容长度吗?如果是这样,javascript不允许设置它,所以我的后续问题将是如何在js中设置...

<!DOCTYPE HTML>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
    <title>Test</title>
</head>
<body>
    <p>Click to select a file</p>
    <form method="post" action="" id="test_form" role="form" 
        enctype="multipart/form-data">
        <input type="file" id="test_file" required><br/><br/>
        <button type="submit" id="test_button">Upload</button>
    </form>

    <script src="js/jquery.js"></script>
    <script>
    $(document).ready(function()
    {
        $("#test_form").on('submit', function(evt)
        {
            var fileElement = $('#test_file');
            var formData = new FormData();
            formData.append("file", fileElement[0].files[0]);

            var req = new XMLHttpRequest();
            req.open("POST", document.URL);
            req.upload.onprogress = function (evt)
            {
                if (evt.lengthComputable)
                {
                    console.log("loaded " + evt.loaded + " total " + evt.total);
                }
                else
                {
                    console.log("progress not computable");
                }
            }
            req.send(formData);
        }); 
    });
    </script>
</body>
</html>

    <?php
    $log_path = "log.txt";
    file_put_contents($log_path, "_FILES:\n" . print_r($_FILES, true) . "\n");
    foreach ($_FILES as $key => $file)
    {
        $src_path = $file["tmp_name"];
        $dst_path = "./files/" . $file["name"];
        file_put_contents($log_path, "save $src_path to $dst_path\n", 
            FILE_APPEND);
        rename($src_path, $dst_path); 
    }
    ?>

服务器在log.txt中报告:

 _FILES:
 Array
 (
     [file] => Array
         (
             [name] => 10.m4v
             [type] => video/mp4
             [tmp_name] => /tmp/phpkooBwd
             [error] => 0
             [size] => 3297694
         )

 )

1 个答案:

答案 0 :(得分:0)

您必须将officeapp = client.DispatchEx("PowerPoint.Application") doc = officeapp.Presentations.Open(source_file,ReadOnly=True,WithWindow=False) doc.SaveAs(target_file, FileFormat=32) doc.Close() officeapp.Quit() 添加到evt.preventDefault()处理程序中。你的html脚本会在提交表单后自动重置页面,你需要停止它。