깜놀하는 해므찌로

Angular file Upload 앵귤러 파일 첨부 구현 예시 / Angular Form 활용 예시 email FormGroup 본문

IT

Angular file Upload 앵귤러 파일 첨부 구현 예시 / Angular Form 활용 예시 email FormGroup

agnusdei1207 2023. 7. 23. 17:55
반응형
SMALL
<div class="flex w-full" (click)="handleUpload()">
	파일첨부
</div>

1. 템플릿에 클릭 이벤트로 달아줍니다.

 

Form = new FormGroup({ // 입력 폼
    name: new FormControl<string>('', [Validators.required]),
    tel: new FormControl<string>('', [Validators.required]),
    email: new FormGroup({
      username: new FormControl<string>('', [Validators.required]),
      domain: new FormControl<string>('', [
        Validators.required,
        Validators.pattern(/([a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*\.[a-zA-Z]{2,})/),
      ]),
    }),
    title: new FormControl<string>('', [Validators.required]),
    content: new FormControl<string>('', [Validators.required]),
    links: new FormControl(),
    document: new FormControl(), // 첨부파일
  });






handleUpload() {
    const input = document.createElement('input'); // input 생성
    input.type = 'file'; // 타입 file 설정
    input.click(); // 생성한 input 클릭

    input.addEventListener('change', (ev) => { // 변경 감지 (파일 선택)
      if (input.files) { // 파일은 배열로 들어오기에 files 속성 체크
        const files = input.files; // 변수 할당

        for (const file of Array.from(files)) {
          const formData = new FormData(); // 데이터 통신을 위해 formData 사용
          formData.append('file', file); // 파일 담기

          this.http // API 통신
            .post('https://서버 호스트/api/upload.php', formData)
            .subscribe({
              next: (data: any) => {
                this.Form.controls['document'].setValue( // 입력 From 값 설정
                  'https://서버 호스트/api/upload.php' + data.url
                );
              },
              error: (error) => {}, 에러 처리
            });
        }
      }
    });
  }

2. 상세 설명은 주석으로 적었습니다.

3. 특이한 점은 Email 의 경우 도메인도 필요하기에 FormGroup 으로 다시 선언한 점 유의하세요!

 

 

<div
    formGroupName="email"
  >
    <div
    >
      이메일*
    </div>
      <input
        formControlName="username"
        maxlength="15"
      />
      <div>@</div>
      <input
        formControlName="domain"
        maxlength="15"
      />
    </div>
  </div>

4. 이메일의 경우 FromGorup 으로 감싼 다음 다시 formControlName 을 부여합니다.

반응형
LIST