@ -1,4 +1,5 @@
const { S3Client , PutObjectCommand } = require ( '@aws-sdk/client-s3' ) ;
const { S3Client , PutObjectCommand } = require ( '@aws-sdk/client-s3' ) ;
const cors = require ( 'cors' ) ;
const crypto = require ( 'crypto' ) ;
const crypto = require ( 'crypto' ) ;
const express = require ( 'express' ) ;
const express = require ( 'express' ) ;
const fs = require ( 'fs' ) ;
const fs = require ( 'fs' ) ;
@ -7,6 +8,8 @@ const path = require('path');
require ( 'dotenv' ) . config ( )
require ( 'dotenv' ) . config ( )
const app = express ( ) ;
const app = express ( ) ;
app . use ( cors ( ) ) ;
const port = 3000 ;
const port = 3000 ;
// Configure AWS
// Configure AWS
@ -33,7 +36,8 @@ app.post('/image', upload.single('image'), (req, res) => {
const hashHex = hashSum . digest ( 'hex' ) ;
const hashHex = hashSum . digest ( 'hex' ) ;
const bucketName = 'gifts-image' ;
const bucketName = 'gifts-image' ;
const fileName = ` ${ hashHex } _ ${ file . originalname } ` ;
console . log ( file . originalname , '=>' , file . path , '=>' , hashHex ) ;
const fileName = hashHex ;
const params = {
const params = {
Body : data ,
Body : data ,
Bucket : bucketName , // S3 Bucket name
Bucket : bucketName , // S3 Bucket name
@ -45,11 +49,23 @@ app.post('/image', upload.single('image'), (req, res) => {
try {
try {
const command = new PutObjectCommand ( params ) ;
const command = new PutObjectCommand ( params ) ;
const response = await s3Client . send ( command ) ;
const response = await s3Client . send ( command ) ;
const finalUrl = ` https:// ${ bucketName } .s3.amazonaws.com/ ${ fileName } ` ;
if ( response . $metadata . httpStatusCode !== 200 ) {
res . send ( JSON . stringify ( { success : true , url : finalUrl } ) ) ;
const errorTime = new Date ( ) . toISOString ( ) ;
console . log ( errorTime , "Error uploading to S3 with bad HTTP status. Metadata:" , response . $metadata ) ;
res . status ( 500 ) . send ( JSON . stringify ( { success : false , message : "Got bad status of " + response . $metadata . httpStatusCode + " from AWS. See server logs at " + errorTime } ) ) ;
} else {
const finalUrl = ` https:// ${ bucketName } .s3.amazonaws.com/ ${ fileName } ` ;
fs . rm ( file . path , ( err ) => {
if ( err ) {
console . error ( "Error deleting temp file" , file . path , "with error:" , err ) ;
}
} ) ;
res . send ( JSON . stringify ( { success : true , url : finalUrl } ) ) ;
}
} catch ( uploadError ) {
} catch ( uploadError ) {
console . error ( 'Error uploading to S3:' , uploadError ) ;
const errorTime = new Date ( ) . toISOString ( ) ;
res . status ( 500 ) . send ( JSON . stringify ( { success : false , message : 'Error uploading file.' } ) ) ;
console . error ( errorTime , "Error uploading to S3:" , uploadError ) ;
res . status ( 500 ) . send ( JSON . stringify ( { success : false , message : "Got error uploading file. See server logs at " + errorTime + " Error Details: " + JSON . stringify ( uploadError ) } ) ) ;
}
}
} ) ;
} ) ;
} ) ;
} ) ;