我正在嘗試將檔案上傳到 S3,但檔案太大,我們需要經常上傳。所以我一直在尋找是否有任何選項可以使用 nodejs 將檔案上傳到 S3,而無需完全讀取檔案的內容。下面的代碼作業正常,但每次我想上傳時它都在讀取檔案。
const aws = require("aws-sdk");
aws.config.update({
secretAccessKey: process.env.ACCESS_SECRET,
accessKeyId: process.env.ACCESS_KEY,
region: process.env.REGION,
});
const BUCKET = process.env.BUCKET;
const s3 = new aws.S3();
const fileName = "logs.txt";
const uploadFile = () => {
fs.readFile(fileName, (err, data) => {
if (err) throw err;
const params = {
Bucket: BUCKET, // pass your bucket name
Key: fileName, // file will be saved as testBucket/contacts.csv
Body: JSON.stringify(data, null, 2),
};
s3.upload(params, function (s3Err, data) {
if (s3Err) throw s3Err;
console.log(`File uploaded successfully at ${data.Location}`);
});
});
};
uploadFile();
uj5u.com熱心網友回復:
您可以使用流。
首先創建要上傳的檔案的 readStream。然后,您可以將其作為 Body 傳遞給 aws s3。
import { createReadStream } from 'fs';
const inputStream = createReadStream('sample.txt');
s3
.upload({ Key: fileName, Body: inputStream, Bucket: BUCKET })
.promise()
.then(console.log, console.error)
uj5u.com熱心網友回復:
您可以使用分段上傳:
AWS 文章: https ://aws.amazon.com/blogs/aws/amazon-s3-multipart-upload/
SO關于python的相同問題:我可以在沒有內容長度標頭的情況下將檔案上傳到S3嗎?
JS API 參考手冊:https ://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3/ManagedUpload.html
基本示例是:
var upload = new AWS.S3.ManagedUpload({
params: {Bucket: 'bucket', Key: 'key', Body: stream}
});
所以你必須提供一個流作為輸入。
const readableStream = fs.createReadStream(filePath);
JS api 記錄在這里:https ://nodejs.org/api/fs.html#fscreatereadstreampath-options
當然,你可以邊讀邊處理資料,然后傳遞給 S3 API,你只需要實作 Stream API。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/452631.html
