1
+ const { GetObjectCommand, PutObjectCommand } = require ( "@aws-sdk/client-s3" ) ;
2
+ const { getSignedUrl } = require ( "@aws-sdk/s3-request-presigner" ) ;
3
+ require ( "dotenv" ) . config ( ) ;
4
+ const asyncHandler = require ( "../middlewares/asyncHandler" ) ;
5
+ const { s3 } = require ( "../configs/s3_config" ) ; // Import the S3 client from config.js
6
+
7
+ const Bucket = process . env . AWS_BUCKET_NAME ; // Your S3 bucket name
8
+ //const Key ='farmpond4.pdf';
9
+ const Expires = 90 ; // URL valid for 60 seconds
10
+ const ContentType = 'application/pdf' ; // Set the content type to PDF
11
+
12
+ //get-upload url
13
+ exports . getUploadUrl = asyncHandler ( async ( req , res ) => {
14
+ const Key = req . query . fileName ;
15
+ if ( ! Key ) {
16
+ return res . status ( 400 ) . json ( { error : "Missing 'fileName' in query params" } ) ;
17
+ }
18
+
19
+ console . log ( Key ) ;
20
+
21
+
22
+ const command = new PutObjectCommand ( { Bucket, Key, ContentType} ) ;
23
+ try {
24
+ const uploadURL = await getSignedUrl ( s3 , command , { Expires} ) ;
25
+ //console.log('Upload URL (Server):', uploadURL);
26
+ //return uploadURL;
27
+ res . json ( uploadURL ) ;
28
+
29
+ } catch ( error ) {
30
+ console . error ( 'Error generating presigned URL' , error ) ;
31
+ //res.status(500).send('Error generating presigned URL');
32
+ throw error ;
33
+ }
34
+ } ) ;
35
+
36
+ //get-download url
37
+ exports . getDownloadUrl = asyncHandler ( async ( req , res ) => {
38
+ const Key = req . query . fileName ;
39
+ const command = new GetObjectCommand ( { Bucket, Key } ) ;
40
+ try {
41
+ const downloadURL = await getSignedUrl ( s3 , command , { Expires } ) ;
42
+ //console.log('Download URL (Server):', downloadURL);
43
+ res . json ( downloadURL ) ;
44
+ } catch ( error ) {
45
+ console . error ( 'Error generating presigned URL' , error ) ;
46
+ //res.status(500).send('Error generating presigned URL');
47
+ throw error ;
48
+ }
49
+ } ) ;
0 commit comments