1. 程式人生 > 其它 >nodejs 實現 AWS S3 上傳、下載、刪除

nodejs 實現 AWS S3 上傳、下載、刪除

技術標籤:B-JavaScriptI-nodenodejsawss3下載上傳

主要使用 aws-sdk 模組,先下載這個模組

npm install --save aws-sdk

const AWS = require("aws-sdk");
const fs = require("fs");

const aws = {
  accessKeyId: "HAIARA2WT12H4E53BLGC",
  secretAccessKey: "a3qhLSMxgAExJfFiWEt2YW8zJdJ8mWlUEh39VTrN",
  bucket: "yu-nan-s3-ex",
  acl: "private",
};

AWS.config.credentials = {
  accessKeyId: aws.accessKeyId,
  secretAccessKey: aws.secretAccessKey,
};
AWS.config.region = "ap-northeast-1";
const s3Client = new AWS.S3();

/**
 * AWS S3檔案儲存
 */
async function saveToS3(tempPath, fileName) {
  return new Promise((resolve, reject) => {
    // 檔案讀取
    fs.readFile(tempPath, (err, data) => {
      if (err) {
        reject(err);
      } else {
        const params = {
          Bucket: aws.bucket,
          Key: fileName,
          Body: data,
          ACL: aws.acl,
        };
        s3Client.upload(params, null, (uploadErr, data) => {
          if (uploadErr) {
            reject(uploadErr);
          } else {
            resolve(data.Location);
          }
        });
      }
    });
  });
}

/**
 * S3檔案刪除
 */
async function deleteS3File(key) {
  const params = { Bucket: aws.bucket, Key: key };

  await s3Client
    .deleteObject(params, (err) => {
      if (err) {
        throw err;
      }
    })
    .promise();
}

/**
 * AWS S3上傳檔案
 */
async function upload(tempPath, fileName) {
  let result = null;
  try {
    result = await saveToS3(tempPath, fileName);
  } catch (error) {
    result = error;
  } finally {
    console.dir(result);
  }
}

/**
 * AWS S3下載檔案
 */
async function downloadFromS3(fileName) {
  return new Promise((resolve, _reject) => {
    const params = { Bucket: aws.bucket, Key: fileName };
    s3Client.getObject(params, (error, data) => {
      if (error) {
        resolve(null);
      }
      if (data) {
        resolve(data.Body);
      }
    });
  });
}

async function download(fileName) {
  let result = null;
  try {
    result = await downloadFromS3(fileName);
  } catch (error) {
    result = error;
  } finally {
    console.dir(result);
  }
}

async function test() {
    await upload('s3.jpg', 'icon/test_s3.jpg');
    await download("icon/test_s3.jpg");
    await deleteS3File("icon/test_s3.jpg");
    await download("icon/test_s3.jpg");
}

test()