[javascript] Draft.js에서 텍스트 에디터의 파일 업로드 및 첨부 기능 구현하기

많은 웹 애플리케이션에서 텍스트 에디터에 파일을 업로드하고 첨부하는 기능은 중요합니다. 이번 블로그 포스트에서는 Draft.js라이브러리를 사용하여 텍스트 에디터에서 파일 업로드 및 첨부 기능을 구현하는 방법을 알아보겠습니다.

1. 파일 업로드 기능 구현하기

사용자가 파일을 업로드할 수 있는 버튼을 텍스트 에디터에 추가해야 합니다. 이를 위해 Draft.js에게 파일 업로드 요청을 전달할 수 있는 커스텀 버튼을 만들어야 합니다.

import { EditorState, ContentState } from 'draft-js';

class MyEditor extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      editorState: EditorState.createEmpty(),
    };
  }

  onFileChange = (e) => {
    const file = e.target.files[0];
    const reader = new FileReader();

    reader.onloadend = () => {
      const contentState = ContentState.createFromText(reader.result);
      const editorState = EditorState.push(
        this.state.editorState,
        contentState,
        'insert-characters'
      );
      this.setState({ editorState });
    };

    reader.readAsText(file);
  };

  render() {
    return (
      <div>
        <input type="file" onChange={this.onFileChange} />
        <Editor
          editorState={this.state.editorState}
          onChange={this.handleChange}
        />
      </div>
    );
  }
}

위의 예제 코드에서 onFileChange 함수는 파일 업로드 이벤트를 처리합니다. 사용자가 선택한 파일을 읽어서 FileReader를 사용하여 파일의 내용을 읽고, 그 내용을 Draft.js의 EditorState에 삽입합니다.

2. 파일 첨부 기능 구현하기

텍스트 에디터에서 파일을 첨부할 수 있는 버튼을 추가하고, 사용자가 버튼을 클릭하면 파일 선택 창을 열도록 해야 합니다.

class MyEditor extends React.Component {
  // ...

  onAttachFile = () => {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = 'image/*';
    input.onchange = this.onFileChange;
    input.click();
  };

  render() {
    return (
      <div>
        <button onClick={this.onAttachFile}>파일 첨부</button>
        <Editor
          editorState={this.state.editorState}
          onChange={this.handleChange}
        />
      </div>
    );
  }
}

위의 예제 코드에서 onAttachFile 함수는 파일 첨부 버튼을 클릭했을 때 호출되는 함수입니다. 함수 안에서는 input 엘리먼트를 생성하고, 이벤트 핸들러를 등록하여 파일 선택 창이 열리도록 합니다. 선택한 파일은 onFileChange 함수를 통해 처리됩니다.

마무리

이제 파일 업로드 및 첨부 기능이 구현된 Draft.js 텍스트 에디터를 사용하여 웹 애플리케이션을 개발할 수 있습니다. 위의 예제 코드를 활용하여 파일 업로드 및 첨부 기능을 구현해보세요.

참고 자료: