使用一个按钮将多个文件上传到S3

时间:2019-01-17 12:39:32

标签: javascript ajax amazon-s3

最近几天我一直在尝试这种方法,但似乎没有用。我需要使用单个按钮上的Ajax请求将多个文件上传到AWS S3。我想向用户提供功能,使他们可以一次上传多个文件。调整代码时,只有一个文件进入S3,而另一个则没有上传。

我尝试将循环添加到Ajax请求中,但它不会遍历多个请求。我还创建了两个单独的Ajax请求,但它们也都失败了。

这是有效的代码,但是在多次上传中确实起作用。

     <form action="https://s3.amazonaws.com/{!awsKeySet.Name}"  method="post" enctype="multipart/form-data" id="uploadForm">
        <input type="hidden"  name="key"  id="key" value="docs/${filename}" /> 
        <input type="hidden" name="AWSAccessKeyId" value="{!awsKeySet.AWS_AccessKey_Id__c}" id="AWSAccessKeyId" /> 
        <input type="hidden"  name="policy" value="{!policy}" /> 
        <input type="hidden"  name="signature" value="{!signedPolicy}" /> 
        <input type="hidden"  name="acl" value="{!acessType}" /> 
        <input type="hidden"  name="Content-Type" value="{!Content_Type}" /> 

        <h4 class="fileToUpload">Select a File to Upload in AWS</h4><br />
        <div class="row">
              <input type="file" size="50" name="file" id="file"  />
        </div>


    <input type="submit" name="submit" value="Submit Form" />
<div id="server-results"> <!-- For server results --> </div>



    </form> 
<div id="upload-progress"><div class="progress-bar"></div></div> <!-- Progress bar added -->




<script>
$(document).ready(function () { 

    $("#uploadForm").submit(function(event){
        event.preventDefault(); //prevent default action 
        var post_url = $(this).attr("action"); //get form action url
        var request_method = $(this).attr("method"); //get form GET/POST method
        var form_data = new FormData(this); //Encode form elements for submission

        $.ajax({
            url : post_url,
            type: request_method,
            data : form_data,
            contentType: false,
            processData:false,
            xhr: function(){
                //upload Progress
                var xhr = $.ajaxSettings.xhr();
                if (xhr.upload) {
                    xhr.upload.addEventListener('progress', function(event) {
                        var percent = 0;
                        var position = event.loaded || event.position;
                        var total = event.total;
                        if (event.lengthComputable) {
                            percent = Math.ceil(position / total * 100);
                        }
                        //update progressbar
                        $("#upload-progress .progress-bar").css("width", + percent +"%");
                    }, true);
                }
                return xhr;
            }
        }).done(function(response){ //
            $("#server-results").html(response);
        });
    });

});

</script>

我需要一种变通办法来一次上传多个文件。任何帮助深表感谢。

0 个答案:

没有答案
相关问题