Angular 11+Spring Boot: 파일 업로드 예

이 자습서에서는 Spring Boot Server를 사용하여 Angular 11 파일을 업로드하고 다운로드하는 예를 보여 줍니다.

개술


Spring Boot Server에 전체 스택 파일을 작성하여 업로드합니다. 사용자는 다음을 수행할 수 있습니다.
  • 업로드 프로세스 참조(백분율)
  • 91678개 파일 (917개) 모두 업로드
  • 클릭 파일명
  • 다운로드

    업로드된 모든 파일은 uploads 폴더에 저장됩니다.

    Angular 11+Spring 부트 파일 업로드 스키마


    다음 아키텍처를 살펴보겠습니다.

    Angular 11 고객:
  • FileUpload 구성 요소 호출UploadService 파일 업로드/다운로드/표시 기능
  • UploadService 사용HttpClientModuleHTTP 요청
  • Spring 부팅 서버:
  • FilesController 클라이언트로부터 HTTP 요청을 받은 후 FilesStorageService 함수를 호출하여 파일을 업로드/다운로드/수령
  • FilesStorageService 자바Files 라이브러리
  • 를 사용하여 파일 시스템을 저장하고 검색하는 기능

    테크니컬


    서버:
  • 자바 8
  • 스프링 부츠2(스프링 웹 MVC 포함)
  • Maven 3.6.1
  • 고객:
  • 각도 11
  • RxJS 6
  • 부팅 4
  • 파일 업로드 및 저장을 위한 Spring Boot Rest API


    API는 Spring Boot 응용 프로그램에서 제공됩니다.
    메서드
    사이트 주소
    행동
    붙이다
    /업로드
    파일 업로드
    얻다
    /파일
    파일 목록 가져오기 (이름과 URL)
    얻다
    /파일/[파일 이름]
    파일 다운로드
    프로젝트 구조입니다.
  • FileInfo 파일을 업로드하는 정보를 포함합니다.
  • FilesStorageService 저장을 초기화하고 새 파일을 저장하며 파일을 불러오고 파일 정보 목록을 얻으며 모든 파일을 삭제할 수 있도록 도와줍니다.
  • FilesController 사용 FilesStorageService 내보내기 Rest API: 파일 게시, 모든 파일에 대한 정보 얻기, 파일 다운로드.
  • FileUploadExceptionAdvice 디렉터가 파일을 업로드하는 동안 예외를 처리합니다.

  • 신청속성은 서브렛 구성의 여러 부분을 포함합니다.

  • 폴.Spring 부트 의존 항목에 대한 xml입니다.
  • 다음 위치에서 Spring 부트 서버를 단계적으로 구현하는 방법을 찾을 수 있습니다.
    Spring Boot Multipart File upload (to static folder) example
    또는: Spring Boot Multipart File upload (to database) example

    Angular 11 파일 업로드/다운로드 사용자 인터페이스 클라이언트


    이것은 우리가 세우고자 하는 프로젝트 구조이다.
  • 응용 프로그램에서 필요한 라이브러리와 구성 요소를 가져옵니다.모듈ts

  • 파일을 업로드합니다.이 서비스는 파일을 저장하고 Spring Boot Server에서 파일을 가져오는 방법을 제공합니다.

  • 파일을 업로드합니다.구성 요소는 업로드 폼, 진도표, 목록 파일의 표시를 포함합니다.

  • 응용 프로그램.구성 요소는 우리가 모든 구성 요소를 끼워 넣는 용기입니다.

  • 색인안내를 가져오는 html입니다.
  • 파일 업로드 서비스
    이 서비스는 AngularHTTPClient를 사용하여 HTTP 요청을 보냅니다.
    다음과 같은 두 가지 기능이 있습니다.
  • upload(file): 진행 상황을 추적하는 데 사용Observable<HttpEvent<any>>
  • getFiles(): 파일 정보 목록을 Observable 대상으로 반환
  • export class UploadFileService {
    
      constructor(private http: HttpClient) { }
    
      upload(file: File): Observable&lt;HttpEvent&lt;any>> {
        ...
      }
    
      getFiles(): Observable&lt;any> {
        ...
      }
    }
    
    파일 업로드에 사용되는 각도 구성 요소
    파일 업로드 구성 요소에는 진행 표시줄, 카드, 단추, 메시지가 있습니다.그것은 UploadFileService를 주입해서 uploadService.upload() 방법을 호출한다.
    업로드 진행률은 event.loadedevent.total에 따라 계산됩니다.
    전송이 완료되면 이벤트는 HttpResponse 대상이 됩니다.이 때, 우리는 uploadService.getFiles()를 호출하여 파일의 정보를 얻고, 결과를 fileInfos 변수에 분배합니다.
    upload() {
      this.progress = 0;
    
      this.currentFile = this.selectedFiles.item(0);
      this.uploadService.upload(this.currentFile).subscribe(
        event => {
          if (event.type === HttpEventType.UploadProgress) {
            this.progress = Math.round(100 * event.loaded / event.total);
          } else if (event instanceof HttpResponse) {
            this.message = event.body.message;
            this.fileInfos = this.uploadService.getFiles();
          }
        },
        err => {
          this.progress = 0;
          this.message = 'Could not upload the file!';
        });
    }
    
    자습서에서 보다 자세한 내용을 확인할 수 있습니다.
    Angular 11 File upload example with progress bar & Bootstrap

    어플리케이션 실행


    다음 명령을 사용하여 Spring 부트 서버를 실행합니다mvn spring-boot:run.
    프로젝트 디렉터리를 새로 고치면 uploads 폴더를 볼 수 있습니다.
    originhttp://localhost:8081에 대한 CORS를 구성하므로 다음 명령을 사용하여 Angular 11 Client를 실행해야 합니다.ng serve --port 8081urlhttp://localhost:8081/를 사용하여 브라우저를 열고 결과를 검사합니다.

    한층 더 읽다

  • https://angular.io/api/common/http/HttpRequest
  • Angular 11 + Spring Boot: Pagination example
  • Angular 11 + Spring Boot: JWT Authentication example
  • Fullstack 때가 낀 애플리케이션:
  • Angular + Spring Boot + MySQL example
  • Angular + Spring Boot + PostgreSQL example
  • Angular + Spring Boot + MongoDB example
  • Firebase에 서버가 없음:
    Angular 11 Upload File to Firebase Storage example

    결론


    오늘은 Angular 11에서 Spring Boot 서버로 파일을 업로드하는 예를 학습했습니다.또한 파일 목록을 표시하고 업로드 진행률을 부트하며 서버에서 파일을 다운로드하는 기능도 제공합니다.
    다음 자습서는 소스 코드가 있는 전체 스택을 구현하는 방법을 보여 줍니다.
  • 백엔드: 파일 업로드Static folder/파일 업로드Database
  • Front-end
  • 여러 파일을 동시에 업로드하려면 다음과 같이 하십시오.

    여기서 설명을 찾을 수 있습니다.
    Angular 11 Multiple Files upload example
    이 두 항목을 한 곳에서 어떻게 운행하는지 알고 싶을 것이다.
    How to Integrate Angular with Spring Boot Rest API
    즐겁게 공부하세요!안녕히 계세요.

    좋은 웹페이지 즐겨찾기