GuíasWeb app
Tutorial: subir archivos a S3 con una URL firmada
1. Firmar (servidor)
import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
import { randomUUID } from 'node:crypto';
const s3 = new S3Client({ region: process.env.S3_REGION, endpoint: process.env.S3_ENDPOINT });
export async function firmar(tipo: string, tamano: number) {
if (!['image/jpeg', 'image/png', 'application/pdf'].includes(tipo)) throw new Error('tipo rechazado');
if (tamano > 10 * 1024 * 1024) throw new Error('demasiado pesado');
const clave = `subidas/${randomUUID()}`;
const url = await getSignedUrl(s3, new PutObjectCommand({ Bucket: process.env.S3_BUCKET, Key: clave, ContentType: tipo }), { expiresIn: 300 });
return { url, clave };
}
2. Enviar (navegador)
const { url, clave } = await (await fetch('/api/firmar', { method: 'POST', body: JSON.stringify({ tipo: f.type, tamano: f.size }) })).json();
await fetch(url, { method: 'PUT', body: f, headers: { 'Content-Type': f.type } });
await fetch('/api/archivos', { method: 'POST', body: JSON.stringify({ clave }) }); // registrar
3. Los ajustes que cuentan
- CORS del bucketPermitir PUT solo desde tu dominio.
- Bucket privadoLa lectura también pasa por URL firmadas.
- Clave elegida por el servidorNunca el nombre de archivo del usuario.
- Caducidad cortaBastan unos minutos.
El marco: crear una web app.
Preguntas frecuentes
- ¿Por qué no enviar el archivo a mi servidor?
- Un archivo pesado ocupa el servidor, su memoria y su ancho de banda. Con la URL firmada, el almacenamiento recibe el archivo directamente.
- ¿Puede el usuario subir cualquier cosa?
- El servidor decide el nombre, el tipo y el tamaño permitidos antes de firmar. Tras la subida, se comprueba el archivo real antes de usarlo.
- ¿Funciona fuera de Amazon?
- Sí, con cualquier almacenamiento compatible con S3: basta con cambiar la dirección del endpoint en el cliente.