尝试删除产品时,S3中的关联文件(图像和PDF)不会在node js中删除

qkf9rpyu  于 11个月前  发布在  Node.js
关注(0)|答案(1)|浏览(172)
const deleteFilesFromS3 = async (fileKeys) => {
  const s3 = new aws.S3({
    accessKeyId: accessKeyId,
    secretAccessKey: secretAccessKey,
    region: region,
  });

  // Iterate through fileKeys and delete each file from S3
  for (const fileKey of fileKeys) {
    const params = {
      Bucket: "thenaturebeautyflower",
      Key: fileKey,
    };

    try {
      await s3.deleteObject(params).promise();
      console.log(`File deleted successfully: ${fileKey}`);
    } catch (error) {
      console.error(`Error deleting file from S3: ${fileKey}`, error);
    }
  }
};

字符串

文件删除成功:https://thenaturebeautyflower.s3.ap-south-1.amazonaws.com/pool/images/%20BERL%C3%8DN%20filter-1702962944491-3-Berlin.jpg ProductState.js:156文件删除成功:https://thenaturebeautyflower.s3.ap-south-1.amazonaws.com/pool/pdf/%20BERL%C3%8DN%20filter-1702962944491-BERLIN.pdf

但仍然图像和pdf文件是目前在s3控制台?

cunj1qz1

cunj1qz11#

const deleteFilesFromS3 = async (fileKeys) => {
  // Creating an S3 client with AWS credentials
  const s3 = new aws.S3({
    accessKeyId: accessKeyId,
    secretAccessKey: secretAccessKey,
    region: region,
  });

  // Specify the common prefix to be removed
  const prefixToRemove = 'https://thenaturebeautyflower.s3.ap-south-1.amazonaws.com/';

  // Iterate through fileKeys and delete each file from S3
  for (const fileKey of fileKeys) {
    // Remove the specified prefix from the file key
    const keyWithoutPrefix = fileKey.replace(prefixToRemove, '');

    // Determine the appropriate prefix based on the file type
    const fileTypePrefix = fileKey.includes('images/') ? 'images/' : 'pdf/';

    // Add the fileTypePrefix to the filename
    const fileName = `${fileTypePrefix}${keyWithoutPrefix.split('/').pop()}`;

    // Specify the parameters for deleting an object from S3
    const params = {
      Bucket: "thenaturebeautyflower",
      Key: keyWithoutPrefix,
      VersionId: 'null'
    };

    console.log(fileName);

    try {
      // Attempt to delete the object from S3
      await s3.deleteObject(params).promise();
      console.log(`File deleted successfully: ${fileKey}`);
    } catch (error) {
      console.error(`Error deleting file from S3: ${fileKey}`, error);
    }
  }
};

字符串
我的错误是,我是puuting完整的地址在filname下的参数,这是错误的,我们应该只包含一个文件夹/filaname. extension只

相关问题