从bootstrap模式直接上传字符串到s3不起作用

时间:2017-08-13 05:36:04

标签: javascript amazon-s3 xmlhttprequest bootstrap-modal aws-sdk

我发现了一种非常奇怪的行为。如果我从web设置一个按钮上传字符串到S3,它可以正常工作。但是如果我从web设置一个按钮来调出一个bootstrap模式,那么从这个模态我设置一个按钮来上传字符串,它不起作用。

在这两种情况下,前端都像下面一样。不同之处在于是单击从web运行函数'saveToAWS'还是从模态运行为2步过程,后者将xhr.status返回为0。

    function saveToAWS() {

  var file = new File([jsonStr], "file.json", { type: "application/json" });

  var xhr = new XMLHttpRequest();
  var fn=file.name;
  var ft = file.type;

  xhr.open("GET", "/sign_s3_save?file-name=" + fn + "&file-type=" + ft);
  xhr.onreadystatechange = function () {

    if (xhr.readyState === 4) {

      if (xhr.status === 200) {
        var response = JSON.parse(xhr.responseText);
        console.log('signiture returned')
        save_file(file, response.signed_request, response.url);
      }
      else {
        alert("Could not get signed URL.");
      }
    }
  };
  xhr.send();
}
function save_file(file, signed_request, url) {


  var xhr = new XMLHttpRequest();
  xhr.open('PUT', signed_request);
  xhr.onreadystatechange = () => {
    if (xhr.readyState === 4) {
      if (xhr.status === 200) {

        console.log('200');
      }
      else {
        alert('cannot upload file');            
      }
    }
  };
  xhr.send(file);
}

Backend as Node.js,以获取签名的URL:

app.get('/sign_s3_save', isLoggedIn, function (req, res) {
    var fileName = req.query['file-name'];
    var fileType = req.query['file-type'];

    aws.config.update({ accessKeyId: AWS_ACCESS_KEY, secretAccessKey: AWS_SECRET_KEY });
    var s3 = new aws.S3();

    var ac = req.user._id;
    var timenow = Date.now().toString();
    var fileRename = ac + '/json/' + timenow + '.json';
    var s3_params = {
        Bucket: S3_BUCKET,
        Key: fileRename,
        Expires: 60,

        ContentType: fileType,
        ACL: 'public-read'
    };
    s3.getSignedUrl('putObject', s3_params, function (err, data) {
        if (err) {
            console.log(err);
        }
        else {
            var return_data = {
                signed_request: data,

                url: 'https://' + S3_BUCKET + '.s3.amazonaws.com/' + fileRename
            };

            res.write(JSON.stringify(return_data));
            res.end();
        }
    });
});

有任何建议吗?

0 个答案:

没有答案