【问题标题】:Split multi-file post with Javascript before upload上传前使用 Javascript 拆分多文件帖子
【发布时间】:2013-01-23 07:42:39
【问题描述】:

我了解多文件上传的 HTML/PHP 方面,但我想我所追求的是一种 Javascript 解决方案,它将文件数组 pre-post 分离并单独将文件发送到单独的 PHP 程序以接收上传和成功/失败反馈,然后再继续。 (即:文件[0] -> POST -> 成功 -> 文件 [1] -> POST -> 成功 -> 等...)

这是我现在用于单个文件的内容 -

    function upload(file){
        var data = new FormData();
        data.append("file", document.getElementById(file).files[0]);
        var xmlHTTP = new XMLHttpRequest();
        xmlHTTP.open("POST", "uploader.php");
        xmlHTTP.send(data);
    }

我意识到最简单的方法是创建多个文件字段,但我想做的是使用 HTML5 中的<input type="file" multiple> 一次批量选择文件列表。如果我只能使用 Javascript 分隔文件,那么只需使用 onreadystatechange 每次都报告成功/失败来循环上述脚本即可。

有什么想法吗?

编辑:
原谅我的狭隘视野,那非常简单!这是我的完整代码,以防它帮助其他人。

<html>
<head>
    <script language="Javascript">
    function multiupload(file){
    count = 0;
    maxcount = document.getElementById(file).files.length;
    alert(maxcount);
    upload(file,count);
    }

    function upload(file,count){
        var data = new FormData();
        data.append("file", document.getElementById(file).files[count]);
        var xmlHTTP = new XMLHttpRequest();
        xmlHTTP.open("POST", "uploader.php");
        xmlHTTP.onreadystatechange=function(){
            if (xmlHTTP.readyState == 4 && xmlHTTP.status == 200){
            count = count+1;
            if(count<maxcount){
            upload(file,count);
            }
            }
        }
        xmlHTTP.send(data);
    }
    </script>
</head>
<body>
    <div id="result"></div>
    <form method="post" action="">
        <input type="file" name="file" id="file" multiple>
        <input type="button" name="submit" value="Upload" onclick="multiupload('file');void(0);">
    </form>
</body>
</html>

【问题讨论】:

  • 你可以摆脱maxcount的逻辑,只需要增加count直到files[count]返回null。

标签: javascript html upload


【解决方案1】:

试试this。您可以开始在成功处理程序中上传下一个文件。这样你就可以做 files[0] -> POST -> Success -> files1 -> POST -> Success

【讨论】:

    【解决方案2】:

    要查看有多少文件,请使用document.getElementById(file).files.length。一旦你循环了很多次,你就上传了所有的文件!这是我的示例:

    <html>
    <head>
    <script language="Javascript">
    function multiupload(file){
    count = 0;
    alert(document.getElementById(file).files.length);
    
    }
    
    </script>
    </head>
    <body>
        <form method="post" action="" enctype="multipart/form-data">
        <input type="file" name="file" id="file" multiple>
        <input type="button" name="submit" value="Upload" onclick="multiupload('file');void(0);">
    </form>
    </body>
    </html>
    

    (来源:https://developer.mozilla.org/en-US/docs/DOM/FileList

    【讨论】:

      猜你喜欢
      • 2011-05-05
      • 2020-09-17
      • 2011-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-06
      • 2021-11-18
      相关资源
      最近更新 更多