具有预签名URL的AWS S3 PUT请求在javascript中不起作用

时间:2019-03-28 23:33:16

标签: javascript jquery amazon-web-services amazon-s3

我正在使用lambda生成预签名的特征,以将文件上传到S3存储桶。当我将Lambda返回的签名与Postman / CURL一起使用时,它可以工作。但是,当我尝试从程序发出PUT请求时,它将本地主机附加到预签名URL。我在本地计算机上使用IIS作为Web服务器。 可能与IIS配置有关吗?还是我在代码或应用程序配置本身中做错了什么?

http://localhost/admin/%22https://sky-testwebsite-upload.s3.amazonaws.com/myfiletoupload.txt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Expires=3600&X-Amz-Date=20190328T231808Z&X-Amz-SignedHeaders=host&X-Amz-Security-Token=FQoGZXIvYXdzEJH%2F%2F%2F%2F%2F%2F%2F%2F%2F%2FwEaDHkQ6M3FyxPqcLENgSLzAUmW1nKDxcQt29OwkBhwPYnGk1GTBXwfMVgGJ1DfeATPyg6QZyxgB02hdPYPFNogxmZ0g4g6EG2mGQrqYAfsLaWJtwyOZU4lS3eQCNlevwjGRqEPehhrfQD8kD5keqiagrA5%2FCAXETN9dSW%2FwQD9%2B%2FOWnBhUTPaHncDt9cRNtm6G64u8htrG9Yzo3d%2FylbbCtEKYAirbrHBOLOzzcq%2FwZWj%2FQ9eq13qiXFYAqZEKiRpl1EPCNZy8dLywOYI0fyatzyf%2FBo5aXO%2BihFNHIfHIO4rpve8KMlvkNGtedsoeUXXP5GJi6vyIRm%2BOKSQH%2BpP8JXyiGqfXkBQ%3D%3D&X-Amz-Credential=ASIAYG7KDJKY75ML2HOH%2F20190328%2Fap-southeast-2%2Fs3%2Faws4_request&X-Amz-Signature=6280eb6f7f2c3cc26ff32ec5a4f542eb1f5a495f2e2efba6006445fe16d4c3e7%22

我的代码如下:

const xhr = new XMLHttpRequest();
xhr.open('PUT', preSignedURL);
xhr.onreadystatechange = () => {
  if(xhr.readyState === 4){
    if(xhr.status === 200){
      alert('File Ready to n upload. xhr.status: ' + xhr.status + 'xhrstatustext:' +xhr.statusText);

    }
    else{

      alert('Could not upload file.');
    }
  }
};
xhr.send(file);

1 个答案:

答案 0 :(得分:0)

我自己弄清楚了。 lambda函数返回的URL格式不正确。我要做的就是删除开头和结尾的引号,然后将文件上传到S3。

var preSignedURL = preSignedURL.substring(1,preSignedURL.length-1);

干杯!