我正在嘗試將檔案上傳到 s3,在此之前我正在更改檔案名。現在我接受來自請求表單資料物件的 2 個檔案,重命名檔案名,并將檔案上傳到 s3。任務結束時,我需要回傳成功上傳的重命名檔案串列。
我正在使用S3.upload()功能。但問題是,最初分配為空陣列的變數將包含重命名的檔案串列。但陣列回傳空回應。這s3.upload()需要很多時間。如果上傳成功,是否有任何可能的解決方案可以存盤檔案名并回傳這些名稱作為回應。
請幫我解決這個問題。代碼看起來像這樣,
if (formObject.files.document && formObject.files.document.length > 0) {
const circleCode = formObject.fields.circleCode[0];
let collectedKeysFromAwsResponse = [];
formObject.files.document.forEach(e => {
const extractFileExtension = ".pdf";
if (_.has(FILE_EXTENSIONS_INCLUDED, _.lowerCase(extractFileExtension))) {
console.log(e);
//change the filename
const originalFileNameCleaned = "cleaning name logic";
const _id = mongoose.Types.ObjectId();
const s3FileName = "s3-filename-convension;
console.log(e.path, "", s3FileName);
const awsResponse = new File().uploadFileOnS3(e.path, s3FileName);
if(e.hasOwnProperty('ETag')) {
collectedKeysFromAwsResponse.push(awsResponse.key.split("/")[1])
}
}
});
};
uj5u.com熱心網友回復:
使用await s3.upload(params).promise();就是解決方案。
uj5u.com熱心網友回復:
使用最新的代碼——AWS SDK for JavaScript V3。這是您應該使用的代碼
// Import required AWS SDK clients and commands for Node.js.
import { PutObjectCommand } from "@aws-sdk/client-s3";
import { s3Client } from "./libs/s3Client.js"; // Helper function that creates Amazon S3 service client module.
import {path} from "path";
import {fs} from "fs";
const file = "OBJECT_PATH_AND_NAME"; // Path to and name of object. For example '../myFiles/index.js'.
const fileStream = fs.createReadStream(file);
// Set the parameters
export const uploadParams = {
Bucket: "BUCKET_NAME",
// Add the required 'Key' parameter using the 'path' module.
Key: path.basename(file),
// Add the required 'Body' parameter
Body: fileStream,
};
// Upload file to specified bucket.
export const run = async () => {
try {
const data = await s3Client.send(new PutObjectCommand(uploadParams));
console.log("Success", data);
return data; // For unit tests.
} catch (err) {
console.log("Error", err);
}
};
run();
更多詳細資訊可以在AWS JavaScript V3 開發指南 中找到。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/360534.html
標籤:javascript 节点.js 亚马逊网络服务 亚马逊-s3
上一篇:S3事件通知中檔案夾的否定
