파일 다운로드는 웹 애플리케이션에서 일반적인 기능이며, 데이터 내보내기, 문서 공유 등에 필수적입니다. 이 안내서에서는 각기 다른 기술을 다루는 각도로 파일을 다운로드하여 특정 요구에 가장 적합한 방법을 선택할 수있는 유연성을 갖도록합니다.
우리가 다이빙하기 전에 다음과 같은 것을 확인하십시오.
Angular Cli 설치
기본 각도 프로젝트 설정
파일을 제공하는 서버 엔드 포인트
먼저, appModule에서 httpclientModule이 가져 오는지 확인하십시오 :
import { HttpClientModule } from '@angular/common/http'; @NgModule({ imports: [ HttpClientModule, // other imports ], }) export class AppModule {}
파일을 처리 할 수있는 서비스를 만듭니다.
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root', }) export class FileService { constructor(private http: HttpClient) {} downloadFile(url: string): Observable{ return this.http.get(url, { responseType: 'blob' }); } }
구성 요소의 서비스를 사용하여 파일을 다운로드합니다 :
import { Component } from '@angular/core'; import { FileService } from './file.service'; @Component({ selector: 'app-file-download', template: ``, }) export class FileDownloadComponent { constructor(private fileService: FileService) {} download() { const url = 'https://example.com/file.pdf'; this.fileService.downloadFile(url).subscribe((blob) => { const a = document.createElement('a'); const objectUrl = URL.createObjectURL(blob); a.href = objectUrl; a.download = 'file.pdf'; a.click(); URL.revokeObjectURL(objectUrl); }); } }
각도로 파일을 다운로드하는 것은 각각 고유 한 이점이있는 다양한 방법을 사용하여 달성 할 수 있습니다. Angular의 내장 httpclient를 선호하든 외부 라이브러리를 활용하든 기술을 이해하면 파일 다운로드를 효과적으로 처리 할 수 있습니다.
부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.
Copyright© 2022 湘ICP备2022001581号-3