Generate Presigned Upload URL
utilcn/generate-presigned-upload-urlFreeUtility
Generate a presigned upload URL for a file.
Install it
npx shadcn@latest add https://utilcn.dev/r/generate-presigned-upload-url.jsonSource
1import { PutObjectCommand } from '@aws-sdk/client-s3';2import { getSignedUrl } from '@aws-sdk/s3-request-presigner';34import { getS3Client } from '@/registry/default/storage/s3-client';56const MAX_FILE_SIZE_BYTES = 10 * 1024 * 1024; // 10MB78type PresignedUrlInput = {9 fileName: string;10 expiresIn?: number;11 contentLength: number;12};1314export async function generatePresignedUploadUrl({15 fileName,16 expiresIn = 3600,17 contentLength,18}: PresignedUrlInput) {19 if (contentLength > MAX_FILE_SIZE_BYTES) {20 throw new Error('File size exceeds maximum allowed limit');21 }2223 try {24 const fileExt = fileName.split('.').pop()?.toLowerCase() ?? '';25 const uniqueId = Date.now().toString();26 const key = fileExt ? `${uniqueId}.${fileExt}` : uniqueId;27 const contentType = getContentType(fileExt);2829 const command = new PutObjectCommand({30 Bucket: process.env.S3_BUCKET_NAME,31 Key: key,32 ContentType: contentType,33 ContentLength: contentLength,34 });3536 const uploadUrl = await getSignedUrl(getS3Client(), command, { expiresIn });37 const fileUrl = `${process.env.S3_PUBLIC_URL}/${key}`;3839 return { uploadUrl, key, fileUrl };40 } catch (err) {41 console.error({ err }, 'Failed to generate presigned upload URL');42 throw new Error('Failed to generate upload URL');43 }44}4546function getContentType(extension: string): string {47 switch (extension) {48 // Images49 case 'jpg':50 case 'jpeg':51 return 'image/jpeg';52 case 'png':53 return 'image/png';54 case 'gif':55 return 'image/gif';56 case 'webp':57 return 'image/webp';58 case 'svg':59 return 'image/svg+xml';6061 // Documents62 case 'pdf':63 return 'application/pdf';64 case 'doc':65 return 'application/msword';66 case 'docx':67 return 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';6869 // Other common types70 case 'json':71 return 'application/json';72 case 'txt':73 return 'text/plain';7475 default:76 return 'application/octet-stream';77 }78}
What it pulls in
npm packages
Files it writes
More from utilcn
All 17 items| Component | Registry | Kind | Access | Installs | Command |
|---|---|---|---|---|---|
| Capitalizecapitalize | utilcn | Utilities | Free | no deps | |
| Capitalize Allcapitalize-all | utilcn | Utilities | Free | no deps | |
| Environment Server Configurationenv-server | utilcn | Utilities | Free | 1 dep | |
| Generate Presigned Download URLgenerate-presigned-download-url | utilcn | Utilities | Free | 2 deps · 2 files | |
| Repeat Padrepeat-pad | utilcn | Utilities | Free | no deps | |
| Reverse Stringreverse-string | utilcn | Utilities | Free | no deps | |
| To Camel Caseto-camel-case | utilcn | Utilities | Free | no deps | |
| To Kebab Caseto-kebab-case | utilcn | Utilities | Free | no deps |
