为什么我在S3上上传时得到空白pdf ?



上传一个pdfblob对象到S3

const params = {
Bucket: "poster-print-bucket",
Key: Date.now().toString() + ".pdf",
Body: blob,
contentType: "application/pdf",
};
const uploaded = await S3.upload(params).promise();

当我打开一个url,即https://poster-print-bucket.s3.ca-central-1.amazonaws.com/1633526785678.pdf它给我下载了一个空白的pdf

我想也许我的blob是损坏或其他东西,但我设法上传相同的blob到firebase存储很好。

btw我使用nextjsapi/upload-poster路由

发生了什么?

使用AWS SDK v3(在本文发布时是最新的),您可以使用PutObjectCommand,它接受Uint8Array作为Body参数(文档)。

将Blob实例转换为ArrayBuffer (docs),并将ArrayBuffer转换为Uint8Array。

代码看起来像:

const { S3Client, PutObjectCommand } = require('@aws-sdk/client-s3');
const client = new S3Client(/* config */);
const arrayBuffer = await blob.arrayBuffer();
const typedArray = new Uint8Array(arrayBuffer);
await client.send(new PutObjectCommand({
Bucket: /* ... */,
Key: /* ... */,
Body: typedArray,
}));

我花了比我愿意承认的更多的时间来解决这个问题。这是解决方案:

前端(在发送到后端之前将blob转换为base64):

function toBase64(blob) {
const reader = new FileReader();
return new Promise((res, rej) => {
reader.readAsDataURL(blob);
reader.onload = function () {
res(reader.result);
};
});
}
toBase64(currentBlob)
.then((blob) => {
return axios
.post("/api/upload-poster", blob, {
headers: {
"Content-Type": "application/pdf",
},
})
.then(({ data }) => data.uploaded.Location);
})

后端:

const base64 = req.body;
const base64Data = Buffer.from(base64.replace(/^data:application/w+;base64,/, ""), "base64");

const params = {
Bucket: "poster-print-bucket",
Key: nanoid() + ".pdf",
Body: base64Data,
ContentEncoding: "base64",
contentType: "application/pdf",
};
const uploaded = await S3.upload(params).promise();

为什么这一切都是必需的?能简单点吗?

相关内容

  • 没有找到相关文章

最新更新