3

我想使用 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>

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

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

如果这不是答案,还会发生什么?

4

0 回答 0