我已经创建了一个将图片上传到s3存储桶的api,但是目前我上传到s3的图片似乎无法读取,因此我猜测它们已损坏?
以下是我的代码:
const AWS = require('aws-sdk')
const s3= new AWS.S3()
const crypto = require("crypto")
const sha1 = data => {
return crypto.createHash("sha1").update(data).digest("hex")
}
const getFile = (ext, buffer, type) => {
let encryptedFileName = sha1(new Buffer(new Date().toString()))
//let timeBasedFileName = new Date().valueOf()
let fileName = encryptedFileName+'.'+ext
let bucketPath = "bucketname/folder/"+type //eg: bucket1/animals/fish
let fileFullPath = bucketPath+"/"+fileName //eg: bucket1/animals/fish/salmon.jpg
let params = {
Bucket: 'mybucket',
Body: buffer,
ContentType: ext==='jpg'||ext==='jpeg'?'image/jpeg':'image/'+ext,
Key: fileName
}
let uploadFile = {
size: buffer.toString('ascii').length,
type: ext==='jpg'||ext==='jpeg'?'image/jpeg':'image/'+ext,
name: fileName,
full_path: fileFullPath
}
return {params,uploadFile}
}
exports.handler = (event, context, callback) => {
let base64String = event.base64String
let ext = base64String.substring("data:image/".length, base64String.indexOf(";base64"))
if (ext===null || (ext!=='jpg' && ext!=='jpeg' && ext!=='gif' && ext!=='png')) {return context.fail('Base64 string is not a supported file type.')}
//pass base64 string into buffer
let buffer = new Buffer(base64String, 'base64')
let file = getFile(ext, buffer, event.type)
//callback(null, 'working fine')
let params = file.params
s3.putObject(params, function(err,data) {
// example response: {"filename":"0242CCB0-CE2E-4C75-A02E-FC054DA9E743.png","status":1,"message":"save success"}
let response = {"statusCode": 400, "filename": "", status: 0, message: "save fail"}
if (err) {callback(err, null)}
response.statusCode=200
response.filename=file.uploadFile.name
response.status=1
response.message="save success"
callback(null, response)
})
}
我基本上是将base64图像字符串转换为缓冲区并上传。 我在这里做错了什么?