AWS S3 JS SDK用于从浏览器上载多个文件

时间:2018-03-26 06:05:01

标签: amazon-web-services amazon-s3 file-upload aws-sdk-js

我想使用AWS S3 JS SDK从浏览器上传多个文件。我可以很好地获得一个文件,但不能获得多个文件。当我选择多个文件时,最后一个文件是唯一一个上传的文件。这是代码:

//head    
<script src="https://sdk.amazonaws.com/js/aws-sdk-2.213.1.min.js"></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.min.js"></script>

//body 
<input type="file" id="file-chooser" multiple />
<button id="upload-button">Upload to S3</button>
<div id="results"></div>
<script type="text/javascript">
AWS.config.region = 'us-east-1';

AWS.config.credentials = new AWS.CognitoIdentityCredentials({
    IdentityPoolId: '###'
});

AWS.config.credentials.get(function(err) {
    if (err) alert(err);
    console.log(AWS.config.credentials);
});

var bucketName = 'c2networkingfiles'; // Enter your bucket name
var bucket = new AWS.S3({
    params: {
        Bucket: bucketName
    }
});

var fileChooser = document.getElementById('file-chooser');
var button = document.getElementById('upload-button');
var results = document.getElementById('results');
button.addEventListener('click', function() {
  var fileArr = fileChooser.files;
  if (fileArr[0]) {
    for (k=0; k<fileArr.length; k++) {
      var file = fileArr[k];
      var fileName = file.name;

      // test to see if file already exists
      var objKey2 = 'testing/' + file.name;
      var objE = new AWS.S3();
      var params2 = {
          Bucket: bucketName,
          Key: objKey2
      };
      objE.headObject(params2, function(err, data) {
        if (data) {
          results.innerHTML = 'File is present. Uploaded on ' + data.LastModified;
          //console.log(data);
        } else {
          //results.innerHTML = '';
          var objKey = 'testing/' + file.name;
          var params = {
              Key: objKey,
              ContentType: file.type,
              Body: file,
              ACL: 'public-read'
          };

          bucket.putObject(params, function(err, data) {
              if (err) {
                results.innerHTML = 'ERROR: ' + err;
              } else {
                //listObjs();
                results.append('SUCCESS! ' + fileName + ' uploaded. <br />');
              }
          });
        }
      });
    }
  } else {
      results.append('Nothing to upload.');
  }
}, false);
</script>

原始代码示例没有循环,我想知道这是否正常工作,因为没有机制等到第一个文件在循环之前完成开始下一次上传。

如果这是答案,有没有办法检查上传状态并等到第一个文件完成后再允许循环?

如果这不是答案,还有什么可能发生?

0 个答案:

没有答案