首页 > 解决方案 > 内部服务器错误 - 通过 aws lambda/api gateway/s3 上传 base64 时

问题描述

我正在尝试通过 aws lambda 将图像上传到 s3。我在 Lambda 中使用下面 url 中的代码,我只更改了变量 fileFullPath 和 Bucket value 。
使用 API 网关、Lambda 函数将图像上传到 S3 存储桶

const AWS = require('aws-sdk');
const s3 = new AWS.S3();
const moment = require('moment');
const fileType = require('file-type');
const sha1 = require('sha1');
const multipart = require('parse-multipart');

exports.handler = function (event, context, callback) {

    let request = event.body;

    // get the request
    let base64String = request.base64String;

    // pass the base64 string into a buffer
    let buffer = new Buffer(base64String, 'base64');

    let fileMime = fileType(buffer);

    // check if the base64 encoded string is a file
    if (fileMime === null) {
        return context.fail('The string supplied is not a file type');
    }

    let file = getFile(fileMime, buffer);
    // let file = getFile(fileMime, parts);
    let params = file.params;

    s3.upload(params, function (err, data) {
    // putObject(params, function (err, data) {
        if (err) {
            console.log(err);
            callback(err);
        }

        // if the file object is uploaded successfully to 
        // s3 then you can get your full url
        console.log('File URL', file.full_path + JSON.stringify(data));
        callback(null, data);

    });
}

let getFile = function (fileMime, buffer) {

    // get the file extension
    let fileExt = fileMime.ext;
    let hash = sha1(new Buffer(new Date().toString()));
    let now = moment().format('YYYY-MM-DD');

    let filePath = hash + '/';
    let fileName = now + '.' + fileExt;
    let fileFullName = filePath + fileName;
    let fileFullPath = 'https://console.aws.amazon.com/s3/buckets/bucket-name/images/' + fileFullName;

    console.log('fileFullPath' + fileFullPath);
    let params = {
        Bucket: 'bucket-name',
        Key: fileFullPath,
        // 'this is simply the filename and the extension, e.g fileFullName + fileExt',
        Body: buffer,
        ContentType: fileMime.mime
    };

    let uploadFile = {
        size: buffer.toString('ascii').length,
        type: fileMime.mime,
        name: fileName,
        full_path: fileFullPath
    }

    return {
        'params': params,
        'uploadFile': uploadFile
    }
}

在此处输入图像描述

此 lambda 函数的执行角色: 在此处输入图像描述

在 API Gateway 中,我只创建资源和方法“POST”,并且在方法请求部分没有设置任何内容。
我已经对此 POST 方法进行了测试,但发生内部服务器错误: 在此处输入图像描述

更新:当前错误来自 cloudwatch

The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object. Received undefined

标签: node.jsamazon-web-servicesamazon-s3aws-lambda

解决方案


对于刚开始使用或学习aws lambda的人,
您可以去cloudwatch查看日志,
其中包含实际错误和“console.log(xxx)”的日志


推荐阅读