Files
frontend/apps/wr/components/lib/useTus_wr/useTusWr.tsx
T

106 lines
3.0 KiB
TypeScript

import {
Upload,
type HttpRequest,
type HttpResponse,
type OnSuccessPayload,
type DetailedError,
} from "tus-js-client";
import { CS_TUS_UPLOAD, CS_URL } from "../config";
import type { FilesType } from "@/components/ui/form/fcltReg/pbnstReg/mngReg/mngRegForm";
import { fetchType, putFectch } from "../api";
import { error } from "console";
import toast from "react-hot-toast";
type UploadOptions = {
handleUploadStart?: (upload: Upload) => void;
handleProgress?: (percentage: string) => void;
handleSuccess?: (payload: OnSuccessPayload) => void;
handleResponse?: (req: HttpRequest, res: ReturnFileType) => void;
};
export type ReturnFileType = {
orgnlFileNm: string;
atflFlieSz: number;
atflType: string;
dwnldNocs: number;
delYn: string;
lnkgDmnId: string | null;
lnkgDmnNm: string | null;
regDt: Date | null;
atflCd: String;
atflSn: number;
atflId: String;
physFileNm: String;
};
export const TusClientUpload = (oFile: FilesType, options?: UploadOptions) =>
new Promise<ReturnFileType>((resolve, reject) => {
try {
const Authorization = "Authorization";
const AUTH_USER_ID = "token-id";
let fileInfo: string | undefined;
//CS_URL
const uploader = new Upload(oFile.file, {
endpoint: CS_TUS_UPLOAD,
chunkSize: 10 * 1024 * 1024,
headers: {
Authorization: "",
AUTH_USER_ID: "",
},
metadata: {
filename: oFile.file.name,
filetype: oFile.file.type,
},
onError(error) {
reject(error);
},
onProgress(bytesUploaded, bytesTotal) {
const percentage = ((bytesUploaded / bytesTotal) * 100).toFixed(2);
options?.handleProgress?.(percentage);
},
onAfterResponse(req, res: HttpResponse) {
fileInfo = res.getHeader("X-File-Info");
if (fileInfo === undefined || fileInfo === null) return;
},
onSuccess(payload: OnSuccessPayload) {
options?.handleSuccess?.(payload);
if (fileInfo) {
const WrTableInfo = {
lnkgDmnNm: "tbWrRuseFcltFile",
lnkgDmnId: "fileTkn",
};
console.log('fileInfo ', fileInfo)
const fileParse = JSON.parse(fileInfo) as ReturnFileType;
putFectch(
`/attach-service/api/v1/atfl/attachments/${fileParse.atflCd}/info`,
WrTableInfo,
fetchType.CS
)
.then((res) => {
resolve(fileParse);
})
.catch((error) => {
reject({
causingError: {
cause: "파일 업로드 업데이트 실패",
},
} as DetailedError);
});
} else reject({} as DetailedError);
},
});
options?.handleUploadStart?.(uploader);
uploader.start();
} catch (e) {
console.log(e);
reject(e as DetailedError);
toast.error(String(e));
}
// setUpload(uploader);
});
//
//