AWS S3에 NodeJS 이미지 업로드를 사용한 Angular - EASY!!

18180 단어 angularnodeawstutorial
Angular 앱의 이미지를 Amazon의 S3 Bucket에 업로드하는 방법이 항상 궁금하셨습니까?

IAM 및 이 튜토리얼을 훨씬 더 길게 만들 다른 보안 항목에 빚을 지지 않고 Angular, NodeJS 및 AWS S3를 사용하여 이를 수행하는 매우 쉬운 방법을 알려드리겠습니다. 그것에 대해 더 알고 싶다면 추가 조사를 하십시오. 실제 프로젝트의 경우 절대 루트 자격 증명을 사용하지 마십시오.

요구 사항:
-Angular CLI 설치
-NodeJS 설치됨
-AWS 계정 보유
-AWS, Angular 및 NodeJS에 대한 기본적인 이해가 있어야 합니다.

AWS





1) AWS 콘솔로 이동합니다.
2) 오른쪽 상단에 계정 이름이 표시되며 클릭한 다음 내 보안 자격 증명을 클릭합니다.

3) 모달이 나타나면 "보안 자격 증명으로 계속"을 클릭합니다.

4) 액세스 키를 클릭합니다.
5) 새 액세스 키 생성을 클릭합니다.

6) 안전한 장소에 키를 복사/붙여넣기합니다.


AWS S3





1) AWS S3 서비스로 이동합니다.
2) 새로운 S3 버킷을 생성합니다.

3) 버킷 이름을 지정하고 NEXT를 클릭한 다음 다시 NEXT를 클릭합니다.

4) 그림과 같이 체크박스를 해제하고 NEXT를 클릭합니다.

5) 버킷 생성을 클릭합니다.


각도 앱





1) 다음 REPO를 복제합니다.
https://github.com/devpato/angular-nodejs-s3-upload

참고: FINAL 폴더 안에 이 프로젝트의 전체 코드가 있습니다. 초소형 앱의 아키텍처를 설정했으므로 시간을 낭비하지 않아도 됩니다.

2) app.component.html로 이동하여 다음 코드를 붙여넣습니다.

참고: 버킷 이름을 갖도록 이미지 소스의 URL을 변경하는 것을 잊지 마십시오.

   <input (change)="onImagePicked($event)" placeholder="Upload Image" 
   type="file" />
   <button (click)="onImageUpload()">Upload Image</button>

    <div *ngIf="imageUrl">
     Preview Image from AWS
     <br />
     <img width="200px" src="https://YOUR S3 BUCKET 
     NAME.s3.amazonaws.com/{{ 
     imageUrl }}" 
     />
    </div>


3) app.component.ts로 이동하여 파일 맨 위에 다음 줄을 붙여넣습니다.

   import { ImageUploadService } from './image-upload.service';


4) app.component.ts로 이동하여 다음 코드를 붙여넣습니다.

   imageObj: File;
   imageUrl: string;

   constructor(private imageUploadService: ImageUploadService) {}

   onImagePicked(event: Event): void {
    const FILE = (event.target as HTMLInputElement).files[0];
    this.imageObj = FILE;
   }

   onImageUpload() {
    const imageForm = new FormData();
    imageForm.append('image', this.imageObj);
    this.imageUploadService.imageUpload(imageForm).subscribe(res => {
      this.imageUrl = res['image'];
    });
   }


5) image-upload.service.ts로 이동하여 다음 코드를 붙여넣습니다.

   imageUpload(imageForm: FormData) {
    console.log('image uploading');
    return this.http.post('http://localhost:3000/api/v1/upload', 
    imageForm);
   }



NodeJS 서버





1) BACKEND라는 폴더로 이동합니다.

참고: 터미널에서 다음을 실행하여 이 프로젝트에 필요한 패키지를 설치하십시오.

   npm i --save multer multer-s3 aws-sdk dotenv nodemon


-multer 및 multer-s3는 사진 업로드를 처리하는 패키지입니다.
-aws-sdk는 AWS 라이브러리에 대한 액세스를 제공합니다.
-dotenv는 환경 변수에 대한 액세스를 제공합니다.

참고: nodemon 패키지는 변경할 때마다 수동으로 서버를 다시 시작할 필요가 없도록 사용자를 위해서만 사용됩니다. 이 패키지는 s3에 이미지를 업로드하는 데 필요하지 않습니다.

2) .env 파일로 이동하여 AWS에서 생성한 KEYS를 입력합니다.

안전한 장소에 보관한 열쇠.

3) service.js 내부에 다음 코드를 붙여넣습니다.

   /* Where image is the name of the property sent from angular via the Form Data and the 1 is the max number of files to upload*/
   app.post('/api/v1/upload', upload.array('image', 1), (req, res) => {
    /* This will be th 8e response sent from the backend to the frontend */
    res.send({ image: req.file });
   });


4) file-upload.js 내부에 다음 코드를 붙여넣습니다.

참고: 다음 코드에서 지역 및 s3 버킷 이름을 변경하는 것을 잊지 마십시오.

   const aws = require('aws-sdk');
   const multer = require('multer');
   const multerS3 = require('multer-s3');
   const dotenv = require('dotenv');
   dotenv.config();

   aws.config.update({
    secretAccessKey: process.env.SECRET_ACCESS_KEY,
    accessKeyId: process.env.ACCESS_KEY_ID,
    region: 'YOUR AWS REGION' //E.g us-east-1
   });

   const s3 = new aws.S3();

   /* In case you want to validate your file type */
   const fileFilter = (req, file, cb) => {
    if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
     cb(null, true);
    } else {
     cb(new Error('Wrong file type, only upload JPEG and/or PNG !'), 
     false);
    }
   };

   const upload = multer({
   fileFilter: fileFilter,
   storage: multerS3({
    acl: 'public-read',
    s3,
    bucket: 'YOUR S3 BUCKET NAME',
    key: function(req, file, cb) {
      /*I'm using Date.now() to make sure my file has a unique name*/
      req.file = Date.now() + file.originalname;
      cb(null, Date.now() + file.originalname);
     }
    })
   });

   module.exports = upload;


5) 마지막으로 server.js 파일에서 파일 맨 위에 다음 줄을 추가합니다.

   const upload = require('./middleware/file-upload');



앱을 테스트할 시간



1) BACKEND 폴더로 이동하고 터미널에서 다음 명령을 실행하여 백엔드 서버를 시작합니다.

   npm start


2) 각도 앱 폴더로 이동하고 터미널에서 다음 명령을 실행하여 백엔드 서버를 시작합니다.

   ng serve --o


참고: 백엔드 및 프런트엔드 서버가 실행 중인지 확인하십시오.

3) Angular 앱이 있는 브라우저에서 이미지를 업로드합니다. 다음이 표시되어야 합니다.



좋은 웹페이지 즐겨찾기