优化上传

This commit is contained in:
none 2023-07-20 15:35:00 +08:00
parent defc71697a
commit de090c63d0
3 changed files with 122 additions and 104 deletions

View File

@ -21,30 +21,10 @@ interface PropsInterface {
onUpdate: () => void; onUpdate: () => void;
} }
interface FileItem {
id: string;
filename: string;
uploadId: string;
name: string;
duration: number;
size: number;
progress: number;
file: File;
resourceType: string;
loading: boolean;
run: UploadChunk;
isSuc: boolean;
isErr: boolean;
errMsg: string;
remoteName: string;
poster: string;
}
export const UploadVideoButton = (props: PropsInterface) => { export const UploadVideoButton = (props: PropsInterface) => {
const [showModal, setShowModal] = useState(false); const [showModal, setShowModal] = useState(false);
const localFileList = useRef<FileItem[]>([]); const localFileList = useRef<FileItem[]>([]);
const [fileList, setFileList] = useState<FileItem[]>([]); const [fileList, setFileList] = useState<FileItem[]>([]);
const upRef = useRef(0);
const getMinioUploadId = async () => { const getMinioUploadId = async () => {
let resp: any = await minioUploadId("mp4"); let resp: any = await minioUploadId("mp4");
@ -55,7 +35,6 @@ export const UploadVideoButton = (props: PropsInterface) => {
multiple: true, multiple: true,
beforeUpload: async (file: File) => { beforeUpload: async (file: File) => {
if (file.type === "video/mp4") { if (file.type === "video/mp4") {
upRef.current++;
// 视频封面解析 || 视频时长解析 // 视频封面解析 || 视频时长解析
let videoInfo = await parseVideo(file); let videoInfo = await parseVideo(file);
// 添加到本地待上传 // 添加到本地待上传
@ -63,58 +42,50 @@ export const UploadVideoButton = (props: PropsInterface) => {
let run = new UploadChunk(file, data["upload_id"], data["filename"]); let run = new UploadChunk(file, data["upload_id"], data["filename"]);
let item: FileItem = { let item: FileItem = {
id: generateUUID(), id: generateUUID(),
duration: videoInfo.duration,
filename: data["filename"],
uploadId: data["upload_id"],
name: file.name,
size: file.size,
progress: 0,
file: file, file: file,
resourceType: data["resource_type"], upload: {
loading: true, handler: run,
run: run, progress: 0,
isSuc: false, status: 0,
isErr: false, remark: "",
errMsg: "", },
remoteName: data["filename"], video: {
poster: videoInfo.poster, duration: videoInfo.duration,
poster: videoInfo.poster,
},
}; };
item.run.on("success", () => { item.upload.handler.on("success", () => {
minioMergeVideo( minioMergeVideo(
item.filename, data["filename"],
item.uploadId, data["upload_id"],
props.categoryIds.join(","), props.categoryIds.join(","),
item.name, item.file.name,
"mp4", "mp4",
item.size, item.file.size,
item.duration, item.video?.duration || 0,
item.poster item.video?.poster || ""
).then(() => { ).then(() => {
item.isSuc = true; item.upload.status = item.upload.handler.getUploadStatus();
setFileList([...localFileList.current]); setFileList([...localFileList.current]);
message.success(`${item.file.name} 上传成功`);
upRef.current--;
}); });
}); });
item.run.on("retry", () => { item.upload.handler.on("progress", (p: number) => {
item.isErr = false; item.upload.status = item.upload.handler.getUploadStatus();
item.errMsg = ""; item.upload.progress = p;
console.log("状态,进度", item.upload.status, item.upload.progress);
setFileList([...localFileList.current]); setFileList([...localFileList.current]);
}); });
item.run.on("progress", (progress: number) => { item.upload.handler.on("error", (msg: string) => {
item.progress = progress; item.upload.status = item.upload.handler.getUploadStatus();
item.upload.remark = msg;
setFileList([...localFileList.current]); setFileList([...localFileList.current]);
}); });
item.run.on("error", (msg: string) => {
item.isErr = true;
item.errMsg = msg;
setFileList([...localFileList.current]);
upRef.current--;
});
setTimeout(() => { setTimeout(() => {
item.run.start(); item.upload.handler.start();
}, 500); }, 500);
// 先插入到ref
localFileList.current.push(item); localFileList.current.push(item);
// 再更新list
setFileList([...localFileList.current]); setFileList([...localFileList.current]);
} else { } else {
message.error(`${file.name} 并不是 mp4 视频文件`); message.error(`${file.name} 并不是 mp4 视频文件`);
@ -124,11 +95,6 @@ export const UploadVideoButton = (props: PropsInterface) => {
}; };
const closeWin = () => { const closeWin = () => {
// if (upRef.current > 0) {
// message.error(`等待上传成功后才能关闭`);
// return;
// }
if (fileList.length > 0) { if (fileList.length > 0) {
let i = 0; let i = 0;
fileList.map((item: any) => { fileList.map((item: any) => {
@ -195,13 +161,16 @@ export const UploadVideoButton = (props: PropsInterface) => {
title: "视频", title: "视频",
dataIndex: "name", dataIndex: "name",
key: "name", key: "name",
render: (_, record) => <span>{record.file.name}</span>,
}, },
{ {
title: "大小", title: "大小",
dataIndex: "size", dataIndex: "size",
key: "size", key: "size",
render: (_, record) => ( render: (_, record) => (
<span>{(record.size / 1024 / 1024).toFixed(2)} M</span> <span>
{(record.file.size / 1024 / 1024).toFixed(2)}M
</span>
), ),
}, },
{ {
@ -210,12 +179,13 @@ export const UploadVideoButton = (props: PropsInterface) => {
key: "progress", key: "progress",
render: (_, record: FileItem) => ( render: (_, record: FileItem) => (
<> <>
{record.progress === 0 && "等待上传"} {record.upload.status === 0 ? (
{record.progress > 0 && ( "等待上传"
) : (
<Progress <Progress
size="small" size="small"
steps={20} steps={20}
percent={record.progress} percent={record.upload.progress}
/> />
)} )}
</> </>
@ -226,32 +196,13 @@ export const UploadVideoButton = (props: PropsInterface) => {
key: "action", key: "action",
render: (_, record) => ( render: (_, record) => (
<> <>
{record.progress > 0 && {record.upload.status === 5 ? (
record.isSuc === false && <Tag color="red">{record.upload.remark}</Tag>
record.isErr === false && ( ) : null}
<Button
type="link"
onClick={() => {
record.run.cancel();
}}
>
</Button>
)}
{record.isErr && ( {record.upload.status === 7 ? (
<> <Tag color="success"></Tag>
<Tag color="red">{record.errMsg}</Tag> ) : null}
<Button
type="link"
onClick={() => {
record.run.retry();
}}
>
</Button>
</>
)}
</> </>
), ),
}, },

View File

@ -11,11 +11,14 @@ export class UploadChunk {
chunkIndex: number; chunkIndex: number;
uploadId: string; uploadId: string;
filename: string; filename: string;
// 上传状态[0:等待上传,3:上传中,5:上传失败,7:上传成功]
uploadStatus: number;
uploadRemark: string;
onError: ((err: string) => void | undefined) | undefined; onError?: (err: string) => void | undefined;
onSuccess: (() => void | undefined) | undefined; onSuccess?: () => void | undefined;
onRetry: (() => void | undefined) | undefined; onRetry?: () => void | undefined;
onProgress: ((progress: number) => void) | undefined; onProgress?: (progress: number) => void;
constructor(file: File, uploadId: string, filename: string) { constructor(file: File, uploadId: string, filename: string) {
this.client = axios.create({ this.client = axios.create({
@ -31,6 +34,9 @@ export class UploadChunk {
this.uploadId = uploadId; this.uploadId = uploadId;
this.filename = filename; this.filename = filename;
this.uploadStatus = 0;
this.uploadRemark = "";
} }
on(event: string, handle: any) { on(event: string, handle: any) {
@ -49,23 +55,25 @@ export class UploadChunk {
if (this.isStop) { if (this.isStop) {
return; return;
} }
// 检测是否上传完成
if (this.chunkIndex > this.chunkNumber) { if (this.chunkIndex > this.chunkNumber) {
//上传完成 this.uploadCompleted();
this.onSuccess && this.onSuccess();
return; return;
} }
this.onProgress &&
this.onProgress( // 进度更新
parseInt((this.chunkIndex / this.chunkNumber) * 100 + "") this.uploadProgressUpdated();
);
let start = (this.chunkIndex - 1) * this.chunkSize; let start = (this.chunkIndex - 1) * this.chunkSize;
const chunkData = this.file.slice(start, start + this.chunkSize); const chunkData = this.file.slice(start, start + this.chunkSize);
const boolname = this.file.name + "-" + this.chunkIndex; const boolname = this.file.name + "-" + this.chunkIndex;
const tmpFile = new File([chunkData], boolname); const tmpFile = new File([chunkData], boolname);
// 首先获取上传minio的签名
minioPreSignUrl(this.uploadId, this.filename, this.chunkIndex) minioPreSignUrl(this.uploadId, this.filename, this.chunkIndex)
.then((res: any) => { .then((res: any) => {
// 拿到签名之后将分块内容上传到minio
return this.client.put(res.data.url, tmpFile, { return this.client.put(res.data.url, tmpFile, {
headers: { headers: {
"Content-Type": "multipart/form-data", "Content-Type": "multipart/form-data",
@ -76,12 +84,15 @@ export class UploadChunk {
this.chunkIndex += 1; this.chunkIndex += 1;
this.start(); this.start();
}) })
.catch((e) => { .catch((e: any) => {
console.error("文件分片上传失败", e); this.uploadedFail(e);
this.onError && this.onError("失败.2");
}); });
} }
isOver() {
return this.uploadStatus === 5 || this.uploadStatus === 7;
}
cancel() { cancel() {
this.isStop = true; this.isStop = true;
this.onError && this.onError("已取消"); this.onError && this.onError("已取消");
@ -92,4 +103,40 @@ export class UploadChunk {
this.start(); this.start();
this.onRetry && this.onRetry(); this.onRetry && this.onRetry();
} }
uploadProgressUpdated() {
if (this.uploadStatus === 0) {
this.uploadStatus = 3;
}
this.onProgress &&
this.onProgress(
parseInt((this.chunkIndex / this.chunkNumber) * 100 + "")
);
}
uploadCompleted() {
this.uploadStatus = 7;
this.onSuccess && this.onSuccess();
}
uploadedFail(e: any) {
console.log("上传失败,错误信息:", e);
this.uploadStatus = 5;
this.onError && this.onError("失败.2");
}
getUploadStatus(): number {
return this.uploadStatus;
}
getUploadProgress(): number {
if (this.chunkNumber === 0) {
return 0;
}
return (this.chunkIndex / this.chunkNumber) * 100;
}
getUploadRemark(): string {
return this.uploadRemark;
}
} }

20
src/playedu.d.ts vendored Normal file
View File

@ -0,0 +1,20 @@
declare global {
interface FileItem {
id: string; //上传文件的唯一id
file: File; //上传的文件资源
// 上传实际执行者
upload: {
handler: UploadChunk;
progress: number;
status: number;
remark: string;
};
// 视频文件信息
video?: {
duration: number; //时长
poster: string; //视频帧
};
}
}
export {};