文件通过Ajax

时间:2018-01-22 10:51:32

标签: javascript python ajax aws-lambda aws-api-gateway

我无法在S3中上传文件。我正在使用如下的ajax调用,

    var fd = new FormData();
    fd.append("file",file_input.files[0])

    $.ajax({
        url: "https://xxxxxxxxxxxxxx.execute-api.ap-xxxx-2.amazonaws.com/xxx/xxx",
        type: 'POST',
        data: fd,
        headers: { "X-API-KEY": apikey},
        contentType: false,
        processType: false,
        success: function(data)
        {
            if(data['result'] === "true")
            {
                $('#issue-error').text('Your report has been submitted successfully.');
                $('#issue-error').css('color','green').show();
                $('form').find("input[type=text], textarea").val("");
            }
        },
    });

此处,URL是带有用Python编写的lamda函数的AWS API。我无法传递文件参数本身。正常参数我可以POST,但不能是文件。

我需要帮助。感谢

2 个答案:

答案 0 :(得分:0)

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
    <CORSRule>
        <AllowedOrigin>*</AllowedOrigin>
        <AllowedMethod>*</AllowedMethod>
        <MaxAgeSeconds>3000</MaxAgeSeconds>
        <AllowedHeader>Authorization</AllowedHeader>
    </CORSRule>
</CORSConfiguration> 

将其放入S3中​​的存储桶配置中。

答案 1 :(得分:0)

我更喜欢使用aws javascript sdk将文件上传到aws,

   AWS.config.credentials = { accessKeyId: "xxxxxxxxxx", secretAccessKey: "xxxxxxxxxxxxxx" }
      AWS.config.region = 'us-west-2';          
      var bucket = new AWS.S3({params: {Bucket: 'bucket-name/folder-name'}});
        var file = fileChooser.files[0];
        if (file) {              
          var params = {
            Key: "example.png",
            ContentType: file.type,
            Metadata: {
              "security-key": "xxxxxxxxxxx"
            } ,
            Body: file
            };
            bucket.upload(params, function (err, data) {
              console.log("file uploaded successfully");                  
            });
        } else {
        }