node.js - 内部服务器错误 - 通过 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
}
}
在 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
解决方案
对于刚开始使用或学习aws lambda的人,
您可以去cloudwatch查看日志,
其中包含实际错误和“console.log(xxx)”的日志
推荐阅读
- javascript - 如何使用模板文字为按钮添加多行文本
- html - 针对容器而不是图像的 css 边距
- javascript - JavaScript - 迭代特定的嵌套数组
- sass - SCSS/SASS 使用嵌套类作为 mixins 的参数
- python - pyc 文件显示“源代码字符串不能包含空字节”
- javascript - 如何使用单个锚标记激活跳转链接并链接到 iframe?
- javascript - 如何获取用户 uid 并在 auth 函数之外打印
- python - 如何将 JSON 数据发布到 PubSub,然后推送到 BigQuery?
- r - 他们是在降价表中使用 ggplot 公式的简单方法吗?
- syntax - 它没有执行并显示语法错误