首页 > 解决方案 > 如何使 AWS S3 上传可重用函数并在我选择的任何文件中使用来自 AWS 的回调?

问题描述

考虑以下 S3 上传代码:

const Category = require('../models/category');
const Link = require('../models/link');
const slugify = require('slugify');
const uuidv4 = require('uuid/v4');
const AWS = require('aws-sdk');

// s3
const s3 = new AWS.S3({
  accessKeyId: process.env.AWS_ACCESS_KEY_ID,
  secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
  region: process.env.AWS_REGION,
});

// Using BASE 64

exports.create = (req, res) => {
  const {image, name, content} = req.body;
   const base64Data = new Buffer.from(
    image.replace(/^data:image\/\w+;base64,/, ''),
    'base64'
  );
  const type = image.split(';')[0].split('/')[1]; // get the png from "data:image/png;base64,"

  // upload image to s3 (The params will be passed to the refactored code)
  const params = {
    Bucket: 'categories-react',
    Key: `category/${uuidv4()}.${type}`,
    Body: base64Data,
    ACL: 'public-read',
    ContentEncoding: 'base64',
    ContentType: `image/${type}`,
  };


  s3.upload(params, (err, data) => {
    if (err) {
      console.log(err);
      res.status(400).json({error: 'Upload to s3 failed'});
    }


    // ... more logic 


    return res.json(success : '....');

  });
};

我想将 AWS 上传代码导出到不同的文件并传递参数而不重复相同的代码,重构代码:

/**
 * Upload image to S3
 */
const AWS = require('aws-sdk');

const uploadImageToS3 = (params) => {
  const s3 = new AWS.S3({
    accessKeyId: process.env.AWS_ACCESS_KEY_ID,
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
    region: process.env.AWS_REGION,
  });

  // ... handle the upload

  s3.upload(params, (err, data) => {
    if (err) {
      console.log(err);
      res.status(400).json({error: 'Upload to s3 failed'});
    }

    // else handle the data ...

  });
};

export {uploadImageToS3 as default};

但是如何在任何文件中使用来自 S3的回调函数将使用 S3 的重构代码?

标签: javascriptnode.jsamazon-web-servicesamazon-s3

解决方案


您必须接受回调作为此函数的参数。

作为建议,不要使用回调,而是尝试使用 Promise API:

s3.upload(params).promise().then(data => {}).catch(err => {})

您将能够从您的函数中返回一个承诺,并在稍后执行 then/catch。


推荐阅读