上传视频最小化

This commit is contained in:
unknown 2024-01-08 13:15:09 +08:00
parent 7820448c0d
commit 9534877350
7 changed files with 347 additions and 200 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 919 B

View File

@ -1,20 +1,8 @@
import { InboxOutlined } from "@ant-design/icons"; import { useEffect, useRef, useState } from "react";
import { import { useSelector } from "react-redux";
Button, import { Button } from "antd";
Col, import { useDispatch } from "react-redux";
message, import { uploadAction } from "../../store/user/loginUserSlice";
Modal,
Progress,
Row,
Table,
Tag,
Upload,
} from "antd";
import Dragger from "antd/es/upload/Dragger";
import { useRef, useState } from "react";
import { generateUUID, parseVideo } from "../../utils";
import { minioMergeVideo, minioUploadId } from "../../api/upload";
import { UploadChunk } from "../../js/minio-upload-chunk";
interface PropsInterface { interface PropsInterface {
categoryIds: number[]; categoryIds: number[];
@ -22,200 +10,32 @@ interface PropsInterface {
} }
export const UploadVideoButton = (props: PropsInterface) => { export const UploadVideoButton = (props: PropsInterface) => {
const [showModal, setShowModal] = useState(false); const dispatch = useDispatch();
const localFileList = useRef<FileItem[]>([]); const uploadStatus = useSelector(
const [fileList, setFileList] = useState<FileItem[]>([]); (state: any) => state.loginUser.value.uploadStatus
);
const getMinioUploadId = async () => { useEffect(() => {
let resp: any = await minioUploadId("mp4"); if (!uploadStatus) {
return resp.data; props.onUpdate();
};
const uploadProps = {
multiple: true,
beforeUpload: async (file: File) => {
if (file.type === "video/mp4") {
// 视频封面解析 || 视频时长解析
let videoInfo = await parseVideo(file);
// 添加到本地待上传
let data = await getMinioUploadId();
let run = new UploadChunk(file, data["upload_id"], data["filename"]);
let item: FileItem = {
id: generateUUID(),
file: file,
upload: {
handler: run,
progress: 0,
status: 0,
remark: "",
},
video: {
duration: videoInfo.duration,
poster: videoInfo.poster,
},
};
item.upload.handler.on("success", () => {
minioMergeVideo(
data["filename"],
data["upload_id"],
props.categoryIds.join(","),
item.file.name,
"mp4",
item.file.size,
item.video?.duration || 0,
item.video?.poster || ""
).then(() => {
item.upload.progress = 100;
item.upload.status = item.upload.handler.getUploadStatus();
setFileList([...localFileList.current]);
});
});
item.upload.handler.on("progress", (p: number) => {
item.upload.status = item.upload.handler.getUploadStatus();
item.upload.progress = p >= 100 ? 99 : p;
setFileList([...localFileList.current]);
});
item.upload.handler.on("error", (msg: string) => {
item.upload.status = item.upload.handler.getUploadStatus();
item.upload.remark = msg;
setFileList([...localFileList.current]);
});
item.upload.handler.start();
// 先插入到ref
localFileList.current.push(item);
// 再更新list
setFileList([...localFileList.current]);
} else {
message.error(`${file.name} 并不是 mp4 视频文件`);
}
return Upload.LIST_IGNORE;
},
};
const closeWin = () => {
if (fileList.length > 0) {
fileList.forEach((item) => {
if (item.upload.status !== 5 && item.upload.status !== 7) {
item.upload.handler.cancel();
}
});
} }
props.onUpdate(); }, [uploadStatus]);
localFileList.current = [];
setFileList([]);
setShowModal(false);
};
return ( return (
<> <>
<Button <Button
type="primary" type="primary"
onClick={() => { onClick={() => {
setShowModal(true); dispatch(
uploadAction({
uploadStatus: true,
uploadCateIds: props.categoryIds,
})
);
}} }}
> >
</Button> </Button>
{showModal ? (
<Modal
width={800}
title="上传视频"
open={true}
onCancel={() => {
closeWin();
}}
maskClosable={false}
closable={false}
onOk={() => {
closeWin();
}}
okText="完成"
>
<Row gutter={[0, 10]}>
<Col span={24}>
<Dragger {...uploadProps}>
<p className="ant-upload-drag-icon">
<InboxOutlined />
</p>
<p className="ant-upload-text"></p>
<p className="ant-upload-hint">
/ mp4
</p>
</Dragger>
</Col>
<Col span={24}>
<Table
pagination={false}
rowKey="id"
columns={[
{
title: "视频",
dataIndex: "name",
key: "name",
render: (_, record) => <span>{record.file.name}</span>,
},
{
title: "大小",
dataIndex: "size",
key: "size",
render: (_, record) => (
<span>
{(record.file.size / 1024 / 1024).toFixed(2)}M
</span>
),
},
{
title: "进度",
dataIndex: "progress",
key: "progress",
render: (_, record: FileItem) => (
<>
{record.upload.status === 0 ? (
"等待上传"
) : (
<Progress
size="small"
steps={20}
percent={record.upload.progress}
/>
)}
</>
),
},
{
title: "操作",
key: "action",
render: (_, record) => (
<>
{record.upload.status === 5 ? (
<>
<Button
type="link"
size="small"
className="b-n-link c-red"
onClick={() => {
record.upload.handler.retry();
}}
>
.
</Button>
</>
) : null}
{record.upload.status === 7 ? (
<Tag color="success"></Tag>
) : null}
</>
),
},
]}
dataSource={fileList}
/>
</Col>
</Row>
</Modal>
) : null}
</> </>
); );
}; };

View File

@ -0,0 +1,26 @@
.float-button {
width: auto;
height: 32px;
background: #ffffff;
box-shadow: 0px 0px 16px 0px rgba(0, 0, 0, 0.1);
border-radius: 16px;
box-sizing: border-box;
padding: 6px 8px;
display: flex;
align-items: center;
position: fixed;
right: 24px;
bottom: 20px;
z-index: 50;
cursor: pointer;
img {
width: 20px;
height: 20px;
}
span {
margin-left: 6px;
font-size: 12px;
font-weight: 400;
color: #ff4d4f;
}
}

View File

@ -0,0 +1,278 @@
import { InboxOutlined } from "@ant-design/icons";
import {
Button,
Col,
message,
Modal,
Progress,
Row,
Table,
Tag,
Upload,
} from "antd";
import Dragger from "antd/es/upload/Dragger";
import { useEffect, useRef, useState } from "react";
import { generateUUID, parseVideo } from "../../utils";
import styles from "./index.module.less";
import { minioMergeVideo, minioUploadId } from "../../api/upload";
import { UploadChunk } from "../../js/minio-upload-chunk";
import { useDispatch } from "react-redux";
import { useSelector } from "react-redux";
import { uploadAction } from "../../store/user/loginUserSlice";
import upIcon from "../../assets/images/commen/upload.png";
export const UploadVideoFloatButton = () => {
const dispatch = useDispatch();
const [showModal, setShowModal] = useState(false);
const localFileList = useRef<FileItem[]>([]);
const intervalId = useRef<number>();
const intervalId2 = useRef<number>();
const [successNum, setSuccessNum] = useState(0);
const [fileList, setFileList] = useState<FileItem[]>([]);
const uploadStatus = useSelector(
(state: any) => state.loginUser.value.uploadStatus
);
const categoryIds = useSelector(
(state: any) => state.loginUser.value.uploadCateIds
);
const getMinioUploadId = async () => {
let resp: any = await minioUploadId("mp4");
return resp.data;
};
useEffect(() => {
if (uploadStatus) {
setShowModal(true);
intervalId.current = setInterval(() => {
let num = localFileList.current.filter(
(it) => it.upload.status === 7
).length;
setSuccessNum(num);
}, 5000);
let timeDiv = document.createElement("div");
document.body.appendChild(timeDiv);
intervalId2.current = setInterval(() => {
timeDiv && timeDiv.click();
}, 10000);
} else {
window.clearInterval(intervalId.current);
window.clearInterval(intervalId2.current);
console.log("定时器已销毁");
}
}, [uploadStatus]);
const uploadProps = {
multiple: true,
beforeUpload: async (file: File) => {
if (file.type === "video/mp4") {
// 视频封面解析 || 视频时长解析
let videoInfo = await parseVideo(file);
// 添加到本地待上传
let data = await getMinioUploadId();
let run = new UploadChunk(file, data["upload_id"], data["filename"]);
let item: FileItem = {
id: generateUUID(),
file: file,
upload: {
handler: run,
progress: 0,
status: 0,
remark: "",
},
video: {
duration: videoInfo.duration,
poster: videoInfo.poster,
},
};
item.upload.handler.on("success", () => {
minioMergeVideo(
data["filename"],
data["upload_id"],
categoryIds.join(","),
item.file.name,
"mp4",
item.file.size,
item.video?.duration || 0,
item.video?.poster || ""
).then(() => {
item.upload.progress = 100;
item.upload.status = item.upload.handler.getUploadStatus();
setFileList([...localFileList.current]);
});
});
item.upload.handler.on("progress", (p: number) => {
item.upload.status = item.upload.handler.getUploadStatus();
item.upload.progress = p >= 100 ? 99 : p;
setFileList([...localFileList.current]);
});
item.upload.handler.on("error", (msg: string) => {
item.upload.status = item.upload.handler.getUploadStatus();
item.upload.remark = msg;
setFileList([...localFileList.current]);
});
item.upload.handler.start();
// 先插入到ref
localFileList.current.push(item);
// 再更新list
setFileList([...localFileList.current]);
} else {
message.error(`${file.name} 并不是 mp4 视频文件`);
}
return Upload.LIST_IGNORE;
},
};
const closeWin = () => {
if (fileList.length > 0) {
fileList.forEach((item) => {
if (item.upload.status !== 5 && item.upload.status !== 7) {
item.upload.handler.cancel();
}
});
}
localFileList.current = [];
setFileList([]);
setSuccessNum(0);
setShowModal(false);
dispatch(
uploadAction({
uploadStatus: false,
uploadCateIds: [],
})
);
};
return (
<>
{uploadStatus ? (
<>
<div
style={{ display: showModal ? "none" : "flex" }}
className={styles["float-button"]}
onClick={() => setShowModal(true)}
>
<img src={upIcon} />
<span>
({successNum}/{fileList.length})
</span>
</div>
<Modal
width={800}
title="上传视频"
open={showModal}
maskClosable={false}
footer={null}
onCancel={() => {
closeWin();
}}
>
<Row gutter={[0, 10]}>
<Col span={24}>
<Dragger {...uploadProps}>
<p className="ant-upload-drag-icon">
<InboxOutlined />
</p>
<p className="ant-upload-text"></p>
<p className="ant-upload-hint">
/ mp4
</p>
</Dragger>
</Col>
<Col span={24}>
<Table
pagination={false}
rowKey="id"
columns={[
{
title: "视频",
dataIndex: "name",
key: "name",
render: (_, record) => <span>{record.file.name}</span>,
},
{
title: "大小",
dataIndex: "size",
key: "size",
render: (_, record) => (
<span>
{(record.file.size / 1024 / 1024).toFixed(2)}M
</span>
),
},
{
title: "进度",
dataIndex: "progress",
key: "progress",
render: (_, record: FileItem) => (
<>
{record.upload.status === 0 ? (
"等待上传"
) : (
<Progress
size="small"
steps={20}
percent={record.upload.progress}
/>
)}
</>
),
},
{
title: "操作",
key: "action",
render: (_, record) => (
<>
{record.upload.status === 5 ? (
<>
<Button
type="link"
size="small"
className="b-n-link c-red"
onClick={() => {
record.upload.handler.retry();
}}
>
.
</Button>
</>
) : null}
{record.upload.status === 7 ? (
<Tag color="success"></Tag>
) : null}
</>
),
},
]}
dataSource={fileList}
/>
</Col>
<Col span={24}>
<div className="r-r-flex">
<Button
type="primary"
onClick={() => {
closeWin();
}}
>
</Button>
<Button
type="default"
className="mr-16"
onClick={() => {
setShowModal(false);
}}
>
</Button>
</div>
</Col>
</Row>
</Modal>
</>
) : null}
</>
);
};

View File

@ -187,6 +187,11 @@ code {
align-items: center; align-items: center;
} }
.r-r-flex {
display: flex;
flex-direction: row-reverse;
}
.flex-1 { .flex-1 {
flex: 1; flex: 1;
} }

View File

@ -5,6 +5,7 @@ import {
SystemConfigStoreInterface, SystemConfigStoreInterface,
saveConfigAction, saveConfigAction,
} from "../../store/system/systemConfigSlice"; } from "../../store/system/systemConfigSlice";
import { UploadVideoFloatButton } from "../../compenents/upload-video-float-button";
interface Props { interface Props {
loginData?: any; loginData?: any;
@ -36,6 +37,7 @@ const InitPage = (props: Props) => {
return ( return (
<> <>
<Outlet /> <Outlet />
<UploadVideoFloatButton></UploadVideoFloatButton>
</> </>
); );
}; };

View File

@ -1,4 +1,5 @@
import { createSlice } from "@reduxjs/toolkit"; import { createSlice } from "@reduxjs/toolkit";
import { message } from "antd";
type UserInterface = { type UserInterface = {
id: number; id: number;
@ -10,12 +11,16 @@ type UserStoreInterface = {
user: UserInterface | null; user: UserInterface | null;
isLogin: boolean; isLogin: boolean;
permissions: string[]; permissions: string[];
uploadStatus: boolean;
uploadCateIds: number[];
}; };
let defaultValue: UserStoreInterface = { let defaultValue: UserStoreInterface = {
user: null, user: null,
isLogin: false, isLogin: false,
permissions: [], permissions: [],
uploadStatus: false,
uploadCateIds: [],
}; };
const loginUserSlice = createSlice({ const loginUserSlice = createSlice({
@ -33,10 +38,21 @@ const loginUserSlice = createSlice({
stage.value.user = null; stage.value.user = null;
stage.value.isLogin = false; stage.value.isLogin = false;
}, },
uploadAction(stage, e) {
if (
stage.value.uploadStatus === true &&
e.payload.uploadStatus === true
) {
message.error("请点击右下角悬浮窗");
}
stage.value.uploadStatus = e.payload.uploadStatus;
stage.value.uploadCateIds = e.payload.uploadCateIds;
},
}, },
}); });
export default loginUserSlice.reducer; export default loginUserSlice.reducer;
export const { loginAction, logoutAction } = loginUserSlice.actions; export const { loginAction, logoutAction, uploadAction } =
loginUserSlice.actions;
export type { UserStoreInterface }; export type { UserStoreInterface };