I have implemented the AWS S3 SDK using Node.js in order to use signed URLs to upload image files to S3. This functionality is working fine but I now need a function that will delete the uploaded object. I have created the below code but it isn't working. In fact it seems that the s3.deleteObject Isn't being called at all although the function is running. I am new to Node so have probably made a silly mistake. Can somebody please help?
Setup template:
AWSTemplateFormatVersion: 2010-09-09
Transform: AWS::Serverless-2016-10-31
Description: S3 Uploader - sample application
Resources:
# HTTP API
MyApi:
Type: AWS::Serverless::HttpApi
Properties:
# CORS configuration - this is open for development only and should be restricted in prod.
# See https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-property-httpapi-httpapicorsconfiguration.html
CorsConfiguration:
AllowMethods:
- GET
- POST
- DELETE
- OPTIONS
AllowHeaders:
- "*"
AllowOrigins:
- "*"
## Lambda functions
UploadRequestFunction:
# More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
Type: AWS::Serverless::Function
Properties:
CodeUri: getSignedURL/
Handler: app.handler
Runtime: nodejs12.x
Timeout: 3
MemorySize: 128
Environment:
Variables:
UploadBucket: !Ref MyAppS3
Policies:
- S3WritePolicy:
BucketName: !Ref MyAppS3
## This permission allows the Lambda function to request signed URLs
## for objects that will be publicly readable. Uncomment if you want this ACL.
- Statement:
- Effect: Allow
Resource: !Sub 'arn:aws:s3:::${MyAppS3}/'
Action:
- s3:putObjectAcl
Events:
UploadAssetAPI:
Type: HttpApi
Properties:
Path: /uploads
Method: get
ApiId: !Ref MyApi
DeleteRequestFunction:
# More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
Type: AWS::Serverless::Function
Properties:
CodeUri: deleteObj/
Handler: app.handler
Runtime: nodejs12.x
Timeout: 3
MemorySize: 128
Environment:
Variables:
DeleteBucket: !Ref MyAppS3
Policies:
- S3WritePolicy:
BucketName: !Ref MyAppS3
- Statement:
- Effect: Allow
Resource: !Sub 'arn:aws:s3:::${MyAppS3}/'
Action:
- s3:putObjectAcl
Events:
deleteAssetAPI:
Type: HttpApi
Properties:
Path: /delete
Method: get
ApiId: !Ref MyApi
## S3 bucket
SMyAppS3:
Type: AWS::S3::Bucket
Properties:
CorsConfiguration:
CorsRules:
- AllowedHeaders:
- "*"
AllowedMethods:
- GET
- PUT
- HEAD
AllowedOrigins:
- "*"
## Take a note of the outputs for deploying the workflow templates in this sample application
Outputs:
APIendpoint:
Description: "HTTP API endpoint URL"
Value: !Sub "https://${MyApi}.execute-api.${AWS::Region}.amazonaws.com"
S3UploadBucketName:
Description: "S3 bucket for application uploads"
Value: !Ref 'MyAppS3'
Delete Object
/*
Deletes objects from the MyApp S3 bucket
*/
'use strict'
const AWS = require('aws-sdk')
AWS.config.update({ region: process.env.AWS_REGION })
const s3 = new AWS.S3()
// Main Lambda entry point
exports.handler = async (event) => {
return await deleteObj(event)
}
const deleteObj = async function(event) {
const params = {
Bucket: process.env.DeleteBucket,
Key: '66910301611586034.jpg'
};
s3.deleteObject(params, function(err, data) {
if (err) {
console.log(err, err.stack);
} else {
console.log('file successfully deleted');
}
});
}
Get Signed Object
'use strict'
const AWS = require('aws-sdk')
AWS.config.update({ region: process.env.AWS_REGION })
const s3 = new AWS.S3()
// Change this value to adjust the signed URL's expiration
const URL_EXPIRATION_SECONDS = 300
// Main Lambda entry point
exports.handler = async (event) => {
return await getUploadURL(event)
}
const getUploadURL = async function(event) {
const randomID = parseInt(Math.random() * 10000000)
const secondsSinceEpoch = Math.round(Date.now() / 1000)
const Key = `${randomID}${secondsSinceEpoch}.jpg`
// Get signed URL from S3
const s3Params = {
Bucket: process.env.UploadBucket,
Key,
Expires: URL_EXPIRATION_SECONDS,
ContentType: 'image/jpeg',
// This ACL makes the uploaded object publicly readable. You must also uncomment
// the extra permission for the Lambda function in the SAM template.
ACL: 'public-read'
}
console.log('Params: ', s3Params)
const uploadURL = await s3.getSignedUrlPromise('putObject', s3Params)
return JSON.stringify({
uploadURL: uploadURL,
Key
})
}
question from:
https://stackoverflow.com/questions/65891283/aws-s3-deleteobject-not-working-using-node-js 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…