Estoy tratando de servir videos e imágenes desde un cubo S3 privado. Puedo descargar los archivos del depósito y, cuando los descargo directamente a través de la interfaz web, funcionan bien, pero cuando uso el SDK para servirlos mediante Express, obtengo un archivo dañado. Actualmente, uso este código para obtener el archivo de S3:
export async function getObjectAsString(key: string): Promise<S3File> { const accessKeyId = process.env.AWS_KEY_ID as string; const secretAccessKey = process.env.AWS_SECRET_KEY as string; const bucketName = process.env.AWS_BUCKET_NAME as string; const client = new S3Client({ region: 'eu-west-1', credentials: { accessKeyId: accessKeyId, secretAccessKey: secretAccessKey, }, }); const response = await client.send( new GetObjectCommand({ Bucket: bucketName, Key: key, }), ); // The code like below should really be provided as nice interfaces by the SDK itself. return new Promise((resolve, reject) => { if (!response.Body) { reject('No Body on response.'); } else { const chunks: Uint8Array[] = []; const bodyStream = response.Body! as Readable; bodyStream.once("error", (error) => reject(error)); bodyStream.on('data', (chunk) => chunks.push(Buffer.from(chunk))); bodyStream.on('end', () => resolve({ file: Buffer.concat(chunks).toString('utf-8'), type: response.ContentType!, length: response.ContentLength!, }), ); } }); }Es una versión ligeramente modificada de esto: https://github.com/aws/aws-sdk-js-v3/issues/1877#issuecomment-1129709683
Luego uso el resultado de esa función en este punto final expreso:
router.get('/media/:id', async (req, res) => { const file = await getObjectAsString(req.params.id); if (!file) { return res.status(404).send({error: 'File not found'}); } writeFileSync('./img.jpeg', file.file); // I use this to debug, this will later be removed res.setHeader('Content-Type', 'image/jpeg').send(file.file); }); Como puede ver, también intenté simplemente escribir la salida en un archivo, pero ese archivo también se corrompió, así que supongo que no estoy recuperando el archivo correctamente. Además, el tipo de S3File se ve así:
type S3File = { file: string, type: string length: number }