Javascript

[Express] AWS S3 Image 업로드하기

eulBlue 2024. 4. 12. 09:49

📱테스트 환경

"express": "^4.18.2"
"typescript": "^5.3.3"

Exprss Server 를 만들고 S3에 이미지를 넣었던 적이 있다.

이때는 이미지 보안때문에 이미지를 base64 로 만들고 해당 이미지를 S3 에 저장했는데

그때 작성한 코드는 다음과 같았다.

export const ImageUpload = (base64: string, imageName: string) => {
  // AWS 설정
  AWS.config.update({
    accessKeyId: process.env.ACCESS_KEY_ID,
    secretAccessKey: process.env.SECRET_ACCESS_KEY,
  });

  // S3 객체 생성
  const s3 = new AWS.S3();

  const buffer = Buffer.from(
    base64.replace(/^data:image\/\w+;base64,/, ""),
    "base64"
  );
  const params = {
    Bucket: bucketname,
    Key: `${imageName}.png`,
    Body: buffer,
    ContentEncoding: "base64",
    ContentType: "image/png",
  };
  const data = s3
    .upload(params, (err: Error, data: any) => {
      if (err) {
        console.log("S3 업로드 에러:", err);
      } else {
        console.log("S3 업로드 성공:", data.Location);
      }
    })
    .promise()
    .then((res) => {
      return res.Location;
    });
  return data;
};

작성하면서도 뭔가 개선할 수 있지 않을까 생각은 했지만, 촉박하게 개발하다보니 그럴 여유가 없었다..
( 해당 코드는 23년 5월에 작성 ... )

내가 생각한 문제는 함수가 호출될때마다 config 가 update 된다는 점

ContentType 이 png 로 고정되어있다는 점

버킷같은 정보가 코드로 박혀있다는 점

base64 로 하고 있다는점 이였다.

base64 의 문제가 파일이 커지면 커질수록 용량이 너무 커져서 속도가 저하가 됐었는데

이를 개선할 수 있는 일이 드디어 생겨버렸다.

S3 업로드 코드를 작성할 일이 생겨서 개선하기 위해서 코드를 작성했는데개선된 코드 내용은 다음과 같다.

// aswConfig.ts
import AWS from "aws-sdk";

const config = {
  accessKeyId: process.env.ACCESS_KEY_ID,
  secretAccessKey: process.env.SECRET_ACCESS_KEY,
  region: "your-region",
};

AWS.config.update(config);

export default AWS;
// uploadImageToS3.ts

import AWS from "./awsConfig";

export const uploadImageToS3 = async (file: Express.Multer.File) => {
  const s3 = new AWS.S3();
  const params = {
    Bucket: process.env.BUCKET,
    Key: file.fieldname,
    Body: file.buffer,
    ContentType: file.mimetype,
  };

  try {
    const { Location } = await s3.upload(params).promise();
    return Location;
  } catch (err) {
    console.error("S3 업로드 에러:", err);
    throw err;
  }
};

Express 에서 Multer 를 사용하였고 Front 단에서는 FormData 를 이용하여

File 을 담아서 보냈다.

 

쌓기만 할 순 없으니 지우기도 해야하는데 해당 내용은 다음 글에서 확인할 수 있다.

 

[Exprss] AWS S3 Image 삭제하기

📱테스트 환경 "express": "^4.18.2" "typescript": "^5.3.3" [Exprss] AWS S3 Image 업로드하기 📱테스트 환경 "express": "^4.18.2" "typescript": "^5.3.3" Exprss Server 를 만들고 S3에 이미지를 넣었던 적이 있다. 이때는 이미

8735.tistory.com