从node.js将图像上传到s3存储桶

时间:2020-09-11 19:14:44

标签: node.js amazon-s3

下面的node.js代码

在“ ap-south-1”地区创建了一个存储分区 您可以在公共场所查看的桶链接:-https://iamgroot007.s3.ap-south-1.amazonaws.com/deadpool.png

const AWS = require("aws-sdk");
const fs = require("fs");
const BUCKET = process.env.BUCKET;
const REGION = process.env.REGION;
const ACCESS_KEY = process.env.ACCESS_KEY_ID;
const SECRET_KEY = process.env.SECRET_ACCESS_KEY;
const localImage = "./ap.png";
const imageRemoteName = `catImage_${new Date().getTime()}.png`;

router.post("/image-upload", (req, res) => {
  AWS.config.update({
    accessKeyId: ACCESS_KEY,
    secretAccessKey: SECRET_KEY,
    region: REGION,
  });

  const s3 = new AWS.S3();

  s3.putObject({
    Bucket: BUCKET,
    Body: fs.readFileSync(localImage),
    Key: imageRemoteName,
  })
    .promise()
    .then((response) => {
      console.log(`done! - `, response);
      console.log(
        `The URL is ${s3.getSignedUrl("getObject", {
          Bucket: BUCKET,
          Key: imageRemoteName,
        })}`
      );
    })
    .catch((err) => {
      console.log("failed:", err);
    });

遇到错误:-

消息: “无法访问的主机:s3.ap-south-1\'. This service may not be available in the ap-south-1,“区域。 代码:“ UnknownEndpoint”, 地区:“ ap-south-1”, 主机名:“ s3.ap-south-1”, 可重试:是的, originalError: {错误:getaddrinfo ENOTFOUND s3.ap-south-1 s3.ap-south-1:443 在GetAddrInfoReqWrap.onlookup上(作为完成时)(dns.js:56:26) 消息:'getaddrinfo ENOTFOUND s3.ap-south-1 s3.ap-south-1:443', errno:“ ENOTFOUND”, 代码:“ NetworkingError”, syscall:“ getaddrinfo”, 主机名:“ s3.ap-south-1”, 主机:“ s3.ap-south-1”, 端口:443, 地区:“ ap-south-1”, 可重试:是的, 时间:2020-09-11T19:08:30.062Z}, 时间:2020-09-11T19:08:30.062Z}

1 个答案:

答案 0 :(得分:0)

有2个错误 1>在.env文件夹中,我在secretKey,accessKey和Bucket名称之后有',' 2>我没有使用multer中间件来接受传入的FormData

用于上传图片的工作代码为:-

const s3 = new AWS.S3({
  accessKeyId: ACCESS_KEY,
  secretAccessKey: SECRET_KEY,
});

const storage = multer.memoryStorage({
  destination: function (req, file, callback) {
    callback(null, "");
  },
});

const upload = multer({ storage }).single("image");

router.post("/image-upload", upload, (req, res) => {
  let fileName = req.file.originalname.split(".");
  const myFileType = fileName[fileName.length - 1];
  const Key = `shopLogo/${uuidv4()}.${myFileType}`;
  console.log(fileName, myFileType, Key, BUCKET);
  const params = {
    Bucket: BUCKET,
    Key,
    Body: req.file.buffer,
  };

  s3.upload(params, (err, data) => {
    if (err) {
      res.status(500).send(err);
    }
    res.status(200).send(data);
  });
});