首页 > 解决方案 > 如何从亚马逊 S3 返回变量

问题描述

我有一个来自亚马逊 S3 的函数,位于一个名为 aws-s3.js 的文件中。

const AWS = require('aws-sdk');
    const fs = require('fs');
    
    const AWSCredentials = {
        accessKey: process.env.AWSAccessKeyId,
        secret: process.env.AWSSecretKey,
        bucketName: 'YOUR_S3_BUCKET_NAME'
    };
    const s3 = new AWS.S3({
        accessKeyId: AWSCredentials.accessKey,
        secretAccessKey: AWSCredentials.secret
    });
    
    const uploadToS3 = (fileName) => {
        // Read content from the file
        const fileContent = fs.readFileSync(fileName.path);
    
        // Setting up S3 upload parameters
        const params = {
            Bucket: AWSCredentials.bucketName,
            Key: fileName.name,
            Body: fileContent
        };
    
         s3.upload(params, function(err, data) {
                if (err) {
                    throw err;
                }
                console.log(`File uploaded successfully. ${data.Location}`);
                return data.Location;
            });
    };
    module.exports= uploadToS3;

我需要将它的执行结果返回给另一个文件(methods.js),也就是说,如果有错误,它返回一个false,否则它返回文件在bd中注册它的路径,我也离开methods.js 的代码

let _insert = async function (req, res, next){
        try{
            const { params } = req;
            if(typeof req.files.detalle_comercio_adherido === 'object'){
                // await upload(req.files.detalle_comercio_adherido);
                 let upload = uploadToS3(req.files.detalle_comercio_adherido);
                    let result = await comAdhServices.insertComAdh(params,new_path);
                        if(result === null){
                            res.json(httpStatus.NOT_FOUND);
                            res.end();
                            return;
                        }
                        res.json(httpStatus.CREATED, result[0]);
                        res.end();
                }
        }catch(err){
            res.send(httpStatus.INTERNAL_SERVER_ERROR, JSON.stringify({Error: httpStatus.INTERNAL_SERVER_ERROR, Message: constants.Error.INTERNALERROR}) );
        }
    };

不幸的是,上传变量中的值总是以未定义的形式到达,如何正确捕获 s3 函数返回的值?

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

解决方案


推荐阅读