如何通过AWS api网关使用参数上传文件?

时间:2018-07-06 07:55:56

标签: aws-lambda multipartform-data aws-api-gateway

我想使用API​​网关上传用户名和文件。因此,我在API网关上创建了一个资源,然后创建了一个方法POST。将方法的主体匹配模板更改为multipart / form-设置了数据和方法直通。

##  See http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html
##  This template will pass through all parameters including path, querystring, header, stage variables, and context through to the integration endpoint via the body/payload
#set($allParams = $input.params())
{
"body-json" : $input.json('$'),
"params" : {
#foreach($type in $allParams.keySet())
    #set($params = $allParams.get($type))
"$type" : {
    #foreach($paramName in $params.keySet())
    "$paramName" : "$util.escapeJavaScript($params.get($paramName))"
        #if($foreach.hasNext),#end
    #end
}
    #if($foreach.hasNext),#end
#end
},
"stage-variables" : {
#foreach($key in $stageVariables.keySet())
"$key" : "$util.escapeJavaScript($stageVariables.get($key))"
    #if($foreach.hasNext),#end
#end
},
"context" : {
    "account-id" : "$context.identity.accountId",
    "api-id" : "$context.apiId",
    "api-key" : "$context.identity.apiKey",
    "authorizer-principal-id" : "$context.authorizer.principalId",
    "caller" : "$context.identity.caller",
    "cognito-authentication-provider" : "$context.identity.cognitoAuthenticationProvider",
    "cognito-authentication-type" : "$context.identity.cognitoAuthenticationType",
    "cognito-identity-id" : "$context.identity.cognitoIdentityId",
    "cognito-identity-pool-id" : "$context.identity.cognitoIdentityPoolId",
    "http-method" : "$context.httpMethod",
    "stage" : "$context.stage",
    "source-ip" : "$context.identity.sourceIp",
    "user" : "$context.identity.user",
    "user-agent" : "$context.identity.userAgent",
    "user-arn" : "$context.identity.userArn",
    "request-id" : "$context.requestId",
    "resource-id" : "$context.resourceId",
    "resource-path" : "$context.resourcePath"
    }
}

我试图上传使用Lambda收到的文件,并使用用户名将上传到我的地址保存在DB中,但是没有用。仅传输文件后,Lambda可以上传它们。

const AWS = require('aws-sdk');
const multipart = require("parse-multipart");
const s3 = new AWS.S3();
const sha1 = require('sha1');
const bluebird = require('bluebird');

exports.handler = function(event, context) {

    let result = []

    var bodyBuffer = new Buffer( event[ 'body-json' ].toString(), 'base64' );

    var boundary = multipart.getBoundary( event.params.header[ 'Content-Type' ] )

    var parts = multipart.Parse( bodyBuffer, boundary )

    let files = getFiles( parts )

    return bluebird.map( files, file => {
        console.log( `uploadCall!!!` )
        return upload( file )
        .then(
            data => {
                result.push( { data, 'file_url': file.uploadFile.full_path } )
                console.log( `data=> ${JSON.stringify( data, null, 2 )}` )
            },
            err => {
                console.log( `s3 upload err => ${err}` )
            }
        )
    })
    .then(_=> {
        return context.succeed(result)
    })
}

let upload = function( file ) {
    console.log( `putObject call!!!!` )
    return s3.upload( file.params ).promise();
};

let getFiles = function( parts ) {
    //let fileExt = 'png'
    let files = [];
    parts.forEach( part => {
        let hash = sha1( new Buffer( new Date().toString() ) );

        let buffer = part.data

        let filePath = hash + '/';

        let fileName = part.filename
        let fileFullName = filePath + fileName;

        let filefullPath = 'bucket address;

        let params = {
            Bucket: 'bucket name',
            Key: fileFullName,
            Body: buffer
        };

        let uploadFile = {
            size: buffer.toString( 'ascii' ).length,
            type: part.type,
            name: fileName,
            full_path: filefullPath
        };

        files.push( { params, uploadFile } )
    } );
    return files
}

我有两个问题

1。如何将以多部分/表单数据格式发送到API网关的对象分为文件和参数

  1. API网关认为文件传输将被限制为大约10Mbps,但超出此能力,您如何将文件上传到S3?

请告知。

0 个答案:

没有答案