'Uploaded image to Heroku app not uploading to s3

I have a website that admin can add images of products to. Heroku deletes said images after a couple of hours so I'm trying to implement AWS s3, to keep images from getting deleted. I'm using multer to upload images.

This is the multer upload .js

import express from "express";
import multer from "multer";
import { isAuth, isAdmin } from "../utils";
import uploadAws from "../uploadAws";

const storage = multer.diskStorage({
  destination(req, file, cb) {
    cb(null, "uploads/");
  },
  filename(req, file, cb) {
    cb(null, `${Date.now()}.jpg`);
  },
});

const upload = multer({ storage });
const uploadRouter = express.Router();

uploadRouter.post("/", isAuth, isAdmin, upload.single("image"), (req, res) => {
  res.status(201).send({ image: `/${req.file.path}` });
  uploadAws( `/${req.file.path}`, `${Date.now()}.jpg`);
});

export default uploadRouter;

And this is the piece for uploading to AWS

import config from "./config";

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

const uploadAws = (path, image) => {

  const s3 = new AWS.S3({
    accessKeyId: config.AWS_ID,
    secretAccessKey: config.AWS_KEY,
  });

  const BUCKET_NAME = "emy-bucket";

  const uploadFile = (fileName) => {
    // Read content from the file
    const fileContent = fs.readFileSync(fileName);

    // Setting up S3 upload parameters
    const params = {
      Bucket: BUCKET_NAME,
      Key: image, // File name you want to save as in S3
      Body: fileContent,
    };

    // Uploading files to the bucket
    s3.upload(params, (err, data) => {
      if (err) {
        throw err;
      }
      console.log(`File uploaded successfully. ${data.Location}`);
    });
  };

  uploadFile(path);
};

export default uploadAws;

here is axios post from api.js file

export const uploadProductImage = async (formData) => {
  try {
    const { token } = getUserInfo();
    const response = await axios({
      url: `${apiUrl}/api/uploads`,
      method: "POST",
      headers: {
        Authorization: `Bearer ${token}`,
        "Content-Type": "multipart/form-data",
      },
      data: formData,
    });
    if (response.statusText !== "Created") {
      throw new Error(response.data.message);
    } else {
      return response.data;
    }
  } catch (err) {
    return { error: err.response.data.message || err.message };
  }
};

The image will upload to the website but not to AWS, any help would be great.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source