2021-10-14 TIL

노성호·2021년 10월 14일
0

동영상 업로드 progress 구현


동영상이나 파일용량이 크면 업로드가 완료되었는지 알 수가 없다. 업로드 로딩 프로그레스를 구현해보았다.

form 또는 input 이벤트

에서 될 줄 알았지만 없었다.

axios

axios.post의 구현부에 들어가 동영상 업로드 프로그레스를 구현 할 수 있을것 같은 코드를 발견했다.

post<T = any, R = AxiosResponse<T>>(url: string, data?: any, config?: AxiosRequestConfig): Promise<R>;

axios.post는 위와같은 매개변수를 가진다. url은 업로드 주소, data는 업로드 할 FormData, config는 무언지 알수 없었지만 코드를 보니

export interface AxiosRequestConfig {
  url?: string;
  method?: Method;
  baseURL?: string;
  transformRequest?: AxiosTransformer | AxiosTransformer[];
  transformResponse?: AxiosTransformer | AxiosTransformer[];
  headers?: any;
  params?: any;
  paramsSerializer?: (params: any) => string;
  data?: any;
  timeout?: number;
  timeoutErrorMessage?: string;
  withCredentials?: boolean;
  adapter?: AxiosAdapter;
  auth?: AxiosBasicCredentials;
  responseType?: ResponseType;
  xsrfCookieName?: string;
  xsrfHeaderName?: string;
  onUploadProgress?: (progressEvent: any) => void;
  onDownloadProgress?: (progressEvent: any) => void;
  maxContentLength?: number;
  validateStatus?: ((status: number) => boolean) | null;
  maxBodyLength?: number;
  maxRedirects?: number;
  socketPath?: string | null;
  httpAgent?: any;
  httpsAgent?: any;
  proxy?: AxiosProxyConfig | false;
  cancelToken?: CancelToken;
  decompress?: boolean;
}

onUploadProgress 발견!!

검색해보니 onUploadProgress의 매개변수는 progressEvent: any인데, 프로퍼티로 number타입의 loaded와 total을 갖고 있었다. loaded는 업로드 되고있는 사이즈, total은 파일의 총 사이즈 일 것 같았다.

const onUploadProgress = (event: any) => setProgress((event.loaded * 100) / event.total);

요렇게 코드를 작성하면된다.
const [progress, setProgress] = useState(0); 으로 프로그레스 퍼센트를 상태 관리해주면 됨.

0개의 댓글