Skip to content

Instantly share code, notes, and snippets.

@wmakeev
Last active May 5, 2023 06:17
Show Gist options
  • Save wmakeev/08b6cd978c400ea56c6ed838cce3eb1f to your computer and use it in GitHub Desktop.
Save wmakeev/08b6cd978c400ea56c6ed838cce3eb1f to your computer and use it in GitHub Desktop.
[Upload to Yandex.Cloud S3 bucket] #yandex #cloud #s3 #upload
import { PutObjectCommand, S3Client } from "@aws-sdk/client-s3";
import mime from "mime-types";
import querystring from "node:querystring";
import { env } from "../env.js";
/*
{
"BUCKET_ENDPOINT": "https://storage.yandexcloud.net",
"BUCKET_REGION": "ru-central1",
"BUCKET_NAME": "my-bucket",
"BUCKET_ACCESS_KEY": "1234EyMGX1234fBh8j1HZ1234",
"BUCKET_ACCESS_SECRET": "1234X42MOKIUCq1234RRhg8KZxyrqSbdJ41234"
}
*/
/**
* Загрузка файла в Яндекс Облако
*
* @param {string} objectKey
* @param {string} fileName
* @param {string} fileContent
* @param {Record<string, string>} tags
*/
export const s3Upload = async (objectKey, fileName, fileContent, tags) => {
const {
BUCKET_ENDPOINT,
BUCKET_REGION,
BUCKET_NAME,
BUCKET_ACCESS_KEY,
BUCKET_ACCESS_SECRET,
} = env;
const s3Client = new S3Client({
endpoint: BUCKET_ENDPOINT,
forcePathStyle: true,
apiVersion: "2006-03-01",
credentials: {
accessKeyId: BUCKET_ACCESS_KEY,
secretAccessKey: BUCKET_ACCESS_SECRET,
},
region: BUCKET_REGION,
});
const mimeType = mime.lookup(fileName) || "application/octet-stream";
const contentDisposition = `attachment; filename="${fileName}"`;
const result = await s3Client.send(
new PutObjectCommand({
Bucket: BUCKET_NAME,
Key: objectKey,
Body: fileContent,
// ACL: 'READ', // При указании выдает ошибку (не обязателен)
StorageClass: "STANDARD",
ContentDisposition: contentDisposition,
ContentType: mimeType,
// Expires: expires,
Tagging: tags ? querystring.stringify(tags) : "",
})
);
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment