我正在嘗試將 Express 端點從aws-sdk for JavaScript 的v2 遷移到 v3 。端點是 AWS S3 的檔案下載器。
在版本 2 中,我將 的結果GetObject以可讀流的形式傳回給瀏覽器。在版本 3 中,同樣的技術失敗并出現錯誤:
型別錯誤:data.Body.createReadStream 不是函式
我如何處理從 new 回傳的資料GetObjectCommand?是一團嗎?我正在努力在v3 SDK 檔案中找到任何有用的東西。
這是端點的兩個版本:
import AWS from 'aws-sdk'
import dotenv from 'dotenv'
import { GetObjectCommand, S3Client } from '@aws-sdk/client-s3'
dotenv.config()
// VERSION 3 DOWNLOADER - FAILS
const getFileFromS3v3 = async (req, res) => {
const client = new S3Client({ region: 'us-west-2' })
const params = {
Bucket: process.env.AWS_BUCKET,
Key: 'Tired.pdf',
}
const command = new GetObjectCommand(params)
try {
const data = await client.send(command)
console.log(data)
data.Body.createReadStream().pipe(res)
} catch (error) {
console.log(error)
}
}
// VERSION 2 DOWNLOADER - WORKS
const getFileFromS3 = async (req, res) => {
const filename = req.query.filename
var s3 = new AWS.S3()
var s3Params = {
Bucket: process.env.AWS_BUCKET,
Key: 'Tired.pdf',
}
// if the file header exists, stream the file to the response
s3.headObject(s3Params, (err) => {
if (err && err.code === 'NotFound') {
console.log('File not found: ' filename)
} else {
s3.getObject(s3Params).createReadStream().pipe(res)
}
})
}
export { getFileFromS3, getFileFromS3v3 }
uj5u.com熱心網友回復:
此版本 3 代碼有效。多虧了一個主要的幫助,訣竅是管道data.Body而不是使用任何 fileStream 方法。
import { GetObjectCommand, S3Client } from '@aws-sdk/client-s3'
import dotenv from 'dotenv'
dotenv.config()
const getFileFromS3 = async (req, res) => {
const key = req.query.filename
const client = new S3Client({ region: process.env.AWS_REGION })
const params = {
Bucket: process.env.AWS_BUCKET,
Key: key,
}
const command = new GetObjectCommand(params)
try {
const data = await client.send(command)
data.Body.pipe(res)
} catch (error) {
console.log(error)
}
}
export { getFileFromS3 }
當從這個前端函式呼叫時,上面的代碼將檔案從 S3 回傳到瀏覽器。
const downloadFile = async (filename) => {
const options = {
url: `/api/documents/?filename=${filename}`,
method: 'get',
responseType: 'blob',
}
try {
const res = await axios(options)
fileDownload(res.data, filename)
} catch (error) {
console.log(error)
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/402130.html
下一篇:在Heroku上反應路由器
