Backend

nestjs에서 alibaba cloud OSS sdk 사용하기 (ali-oss)

하우아유두잉 2023. 6. 28. 17:43

 

AWS S3를 이용하다가, 중국 진출과 함께 Alibaba Cloud의 클라우드 데이터 스토리지 서비스인 OSS로 이전하게 되었다.

 

그래서 기존 S3와 연동된 소스코드도 수정을 해야 했다.

 

다행히 알리바바에서 SDK를 지원해주고, 기존 코드를 크게 고치지 않아도 연동이 된다.

 

목표는, OSS에 이미지 파일을 업로드 하는 것이다.

 


 

1. 모듈 설치 (https://www.npmjs.com/package//ali-oss?activeTab=readme)

npm install ali-oss --save

 

2. 사전 인터페이스 및 OSS 서비스 작성

// IFile.ts
export interface IFile {
  encoding: string;
  buffer: Buffer;
  fieldname: string;
  mimetype: string;
  originalname: string;
  size: number;
}
// ali-oss.service.ts
...
import OSS = require('ali-oss');

@Injectable()
export class AliOSSService {
  private readonly oss: OSS;
  private readonly uploadImagePath: String;
  
  constructor(
    public configService: ApiConfigService,
  ) {
    const aliOssConfig = configService.aliOssConfig;

    this.oss = new OSS({
      region: aliOssConfig.bucketRegion,
      accessKeyId: aliOssConfig.accessKey,
      accessKeySecret: aliOssConfig.secretKey,
      bucket: aliOssConfig.bucketName,
      endpoint: aliOssConfig.endpoint,
    });

    this.uploadImagePath = aliOssConfig.uploadImagePath;
  }

  async uploadImage(file: IFile) {
    try {
      const result = await this.oss.put(
        this.uploadImagePath+hash(file.originalname), 
        file.buffer
      );
      return result;
    } catch (e) {
      console.log(e);
    }
  }
  
}

 

3. controller 작성

//controller.ts
@Post('oss')
@UseInterceptors(FileInterceptor('image'))
uploadImageOSS(@UploadedFile() image: IFile) {
  return this.imageUploadService.uploadImageOSS(image);
}

 

4. service 작성

// service.ts
...
import { AliOSSService } from '**/ali-oss.service';

@Injectable()
export class ImageUploadService {
  constructor(
	...
    private readonly aliOSSService: AliOSSService,
    ) {}

async uploadImageOSS(image: IFile) {

    if(image === undefined || image === null) {
        throw new NotFoundException("Not Found!");
    }
    
    const uploadedInfo = await this.aliOSSService.uploadImage(image);
    
    // 아래 양식은 자유입니다.
    return {
      image_url: uploadedInfo?.url,
      message: "성공관련 메시지!",
      field: "image",
      name: uploadedInfo?.name ? path.basename(uploadedInfo?.name) : "",
    };
  }

 

postman으로 테스트 해보면 아래와 같은 결과가 나온다.

 

알리바바 클라우드 콘솔에서 확인해보면 된다.

 


아 그리고을 하나 남기자면,

ACL(Access Control List)를 private 또는 inherited from Bucket을 한 경우 해당 파일마다 생성되는 access-key가 있지 않는 한, 알리바바 클라우드 외부에서의 접근이 제한된다.

선택된 파일의 ACL 선택란
파일 URL로 브라우저 접속시 제한

 

이런 경우 ECS(AWS의 EC2)에서는 접근이 가능하도록 할 수 있다.

1. 먼저 RAM(AWS의 IAM)에서 사용자 권한을 설정한다.

 

 

각자의 상황과 환경에 맞춰서 지정하면 된다.

 

 

2. 그리고 다시 OSS의 Bucket Policy 설정 탭으로 이동한다.

 

 

3. 그리고 Authorize 버튼을 클릭한다.

 

4. 다음과 같이 RAM User 설정과 VPC를 지정해준다.

 

이렇게 해주면 내부 환경인 ECS, 정확히 말하면 설정된 VPC 환경 내에서 접근이 가능하다.

 

 

5. 테스트

ECS에 접속해 curl으로 다운로드를 해보자.

다운로드 된 것을 확인 할 수 있다.

 

 

 

 


참고 사이트 공유

https://www.npmjs.com/package//ali-oss 

 

ali-oss

aliyun oss(object storage service) node client. Latest version: 6.17.1, last published: a year ago. Start using ali-oss in your project by running `npm i ali-oss`. There are 1297 other projects in the npm registry using ali-oss.

www.npmjs.com



https://www.alibabacloud.com/help/en/object-storage-service/latest/getting-started-with-oss-sdk-for-node-js

 

Getting started with OSS SDK for Node.js - Object Storage Service - Alibaba Cloud Documentation Center

This topic describes how to manage Object Storage Service (OSS) in the Node.js environment, such as listing buckets and uploading objects. PrerequisitesOSS SDK for Node.js is initialized. For more information, see Initialization. List bucketsThe following

www.alibabacloud.com

https://www.alibabacloud.com/help/en/object-storage-service/latest/node-js-quick-start

 

Getting started with OSS SDK for Node.js - Object Storage Service - Alibaba Cloud Documentation Center

This topic describes how to manage Object Storage Service (OSS) in the Node.js environment, such as listing buckets and uploading objects. PrerequisitesOSS SDK for Node.js is initialized. For more information, see Initialization. List bucketsThe following

www.alibabacloud.com

https://www.alibabacloud.com/help/en/object-storage-service/latest/migrate-from-s3-to-oss

 

Migrate data from Amazon S3 to Alibaba Cloud OSS - Object Storage Service - Alibaba Cloud Documentation Center

Alibaba Cloud Object Storage Service (OSS) is compatible with the Amazon Simple Storage Service (Amazon S3) API operations to allow you to seamlessly migrate data from S3 to OSS. Usage notesLimitsOSS is compatible with the S3 protocol. You can create bucke

www.alibabacloud.com

https://www.alibabacloud.com/help/en/object-storage-service/latest/initiate-a-request

 

Initiate requests - Object Storage Service - Alibaba Cloud Documentation Center

Search How helpful was this page? $!csrfToken.hiddenField What might be the problems? More suggestions? Send Feedback Thank you! We've received your feedback.

www.alibabacloud.com