MainComponent.js
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,
};
}
...
다음으로 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);
}
...
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,
});
}
...
class MainComponent extends Component {
...
componentDidMount() {
UploadService.getFiles().then((response) => {
this.setState({
fileInfos : response.data,
});
});
}
파일 업로드 UI의 렌더링 구현은 생략하겠습니다.
결과 화면 ( React Slick을 이용하였습니다. )