[React] 이미지 업로드 UI 만들기

챠밍·2021년 2월 18일
0

이번 포스팅에서는 Rest API를 가지고 서버에서 불러온 json data값을 화면에 출력하는 컴포넌트를 만들어 보겠습니다. ( Rest API 참고 )

MainComponent.js 
  1. constructor()메서드 내부에 상태를 정의합니다.
import React, {Component} from "react";
import UploadService from "../service/upload-files.service";

class MainComponent extends Component {
    constructor(props) {
        super(props);
        this.selectFile = this.selectFile.bind(this);
        this.upload = this.upload.bind(this);

        this.state = {
            selectedFiles: undefined,
            currentFile: undefined,
            progress: 0,
            message: "",
            loading: false,
            fileInfos: null,
        };
    }
    ...
  1. 다음으로 selectFile()에서 선택한 파일을 가져 오는 데 도움이되는 메서드를 정의합니다.

  class MainComponent extends Component {
  
  ...
  
  selectFile(event)
    {
        event.preventDefault();
        let reader = new FileReader();
        let file = event.target.files[0];
        reader.onloadend = () => {
            this.setState({
                selectedFiles: event.target.files,
                file : file,
                previewURL : reader.result
            })
        }
        reader.readAsDataURL(file);
    }
    ...
  1. selectedFiles은 파일을 액세스 하는 데 사용 합니다. 그런 다음 callback을 사용하여 UploadService.upload()메서드를 통해 currentFile을 호출합니다.
class MainComponent extends Component {
  
  ...
  
upload()
    {
        let currentFile = this.state.selectedFiles[0];

        this.setState({
            progress: 0,
            currentFile: currentFile,
        });
        UploadService.upload(currentFile, (event) => {
            this.setState({
                progress: Math.round((100 * event.loaded) / event.total),
            });
        }).then((response) => {
            this.setState({
                fileInfos: response,
            });
            return UploadService.getFiles();
        }).catch(() => {
            this.setState({
                progress: 0,
                message: "upload the file!",
                currentFile: undefined,
            });
        }).finally(() => {
            this.setState({
                loading:true,
            })
        });

        this.setState({
            selectedFiles: undefined,
        });
    }
    ...
  1. 작업을 componentDidMount()방법으로 수행해야합니다. 외부에서 데이터를 불러와야 할때 사용하기 적절합니다.
class MainComponent extends Component {
  
  ...
  
 componentDidMount() {
        UploadService.getFiles().then((response) => {
            this.setState({
                fileInfos : response.data,
            });
        });
    
    }

파일 업로드 UI의 렌더링 구현은 생략하겠습니다.


결과 화면 ( React Slick을 이용하였습니다. )

profile
SW developer

0개의 댓글