|
|
@ -1,4 +1,5 @@ |
|
|
|
const AWS = require('aws-sdk'); |
|
|
|
const { S3Client, PutObjectCommand } = require('@aws-sdk/client-s3'); |
|
|
|
const crypto = require('crypto'); |
|
|
|
const express = require('express'); |
|
|
|
const fs = require('fs'); |
|
|
|
const multer = require('multer'); |
|
|
@ -9,13 +10,14 @@ const app = express(); |
|
|
|
const port = 3000; |
|
|
|
|
|
|
|
// Configure AWS
|
|
|
|
AWS.config.update({ |
|
|
|
accessKeyId: process.env.AWS_ACCESS_KEY, |
|
|
|
secretAccessKey: process.env.AWS_SECRET_KEY, |
|
|
|
const s3Client = new S3Client({ |
|
|
|
region: process.env.AWS_REGION, |
|
|
|
credentials: { |
|
|
|
accessKeyId: process.env.AWS_ACCESS_KEY, |
|
|
|
secretAccessKey: process.env.AWS_SECRET_KEY |
|
|
|
} |
|
|
|
}); |
|
|
|
|
|
|
|
const s3 = new AWS.S3(); |
|
|
|
const upload = multer({ dest: 'uploads/' }); |
|
|
|
|
|
|
|
// POST endpoint to upload an image
|
|
|
@ -23,23 +25,32 @@ app.post('/image', upload.single('image'), (req, res) => { |
|
|
|
const file = req.file; |
|
|
|
|
|
|
|
// Read the file from the temporary location
|
|
|
|
fs.readFile(file.path, (err, data) => { |
|
|
|
fs.readFile(file.path, async (err, data) => { |
|
|
|
if (err) throw err; // Handle error
|
|
|
|
|
|
|
|
const hashSum = crypto.createHash('sha256'); |
|
|
|
hashSum.update(data); |
|
|
|
const hashHex = hashSum.digest('hex'); |
|
|
|
|
|
|
|
const bucketName = 'gifts-image'; |
|
|
|
const fileName = `${hashHex}_${file.originalname}`; |
|
|
|
const params = { |
|
|
|
Bucket: 'gifts-image', // S3 Bucket name
|
|
|
|
Key: `${Date.now()}_${path.basename(file.originalname)}`, // File name to use in S3
|
|
|
|
Body: data, |
|
|
|
//ACL: 'public-read' // Optional: if you want the uploaded file to be publicly accessible
|
|
|
|
Bucket: bucketName, // S3 Bucket name
|
|
|
|
ContentType: file.mimetype, // File content type
|
|
|
|
Key: fileName, // File name to use in S3
|
|
|
|
}; |
|
|
|
|
|
|
|
// Upload the file to S3
|
|
|
|
s3.upload(params, function(s3Err, data) { |
|
|
|
if (s3Err) throw s3Err; // Handle upload error
|
|
|
|
|
|
|
|
// Once successfully uploaded to S3, send back the URL of the uploaded file
|
|
|
|
res.send(`File uploaded successfully at ${data.Location}`); |
|
|
|
}); |
|
|
|
try { |
|
|
|
const command = new PutObjectCommand(params); |
|
|
|
const response = await s3Client.send(command); |
|
|
|
const finalUrl = `https://${bucketName}.s3.amazonaws.com/${fileName}`; |
|
|
|
res.send(JSON.stringify({ success: true, url: finalUrl })); |
|
|
|
} catch (uploadError) { |
|
|
|
console.error('Error uploading to S3:', uploadError); |
|
|
|
res.status(500).send(JSON.stringify({ success: false, message: 'Error uploading file.' })); |
|
|
|
} |
|
|
|
}); |
|
|
|
}); |
|
|
|
|
|
|
|