init: 0.0.8
feat: 实现了分片上传 todo: 1. 上传完成后 code 回显 2. 清理不用的临时 code file 3. 断点续传 4. 多 chunk 并发上传
This commit is contained in:
@ -1,5 +1,5 @@
|
||||
import {FileSharing} from "./page/share.tsx";
|
||||
|
||||
export function App() {
|
||||
return <FileSharing />;
|
||||
return <FileSharing />
|
||||
}
|
33
frontend/src/component/button/u-button.tsx
Normal file
33
frontend/src/component/button/u-button.tsx
Normal file
@ -0,0 +1,33 @@
|
||||
import React, {ReactNode} from 'react';
|
||||
import {createUseStyles} from "react-jss";
|
||||
|
||||
const useStyle = createUseStyles({
|
||||
ubutton: {
|
||||
backgroundColor: "#4CAF50",
|
||||
color: "white",
|
||||
padding: "10px 20px",
|
||||
border: "none",
|
||||
borderRadius: "5px",
|
||||
cursor: "pointer",
|
||||
transition: "background-color 0.3s",
|
||||
"&:hover": {
|
||||
backgroundColor: "#45a049",
|
||||
},
|
||||
"&:disabled": {
|
||||
backgroundColor: "#a5d6a7",
|
||||
cursor: "not-allowed",
|
||||
},
|
||||
}
|
||||
})
|
||||
type Props = {
|
||||
onClick: () => void;
|
||||
children: ReactNode;
|
||||
disabled?: boolean;
|
||||
style?: React.CSSProperties | undefined;
|
||||
};
|
||||
export const UButton: React.FC<Props> = ({onClick, children, style,disabled = false}) => {
|
||||
const classes= useStyle()
|
||||
return <button style={style} className={classes.ubutton} disabled={disabled} onClick={onClick}>
|
||||
{children}
|
||||
</button>
|
||||
}
|
126
frontend/src/component/message/u-message.tsx
Normal file
126
frontend/src/component/message/u-message.tsx
Normal file
@ -0,0 +1,126 @@
|
||||
import {createRoot} from "react-dom/client";
|
||||
import {useEffect, useState} from "react";
|
||||
import {createUseStyles} from "react-jss";
|
||||
|
||||
const useStyle = createUseStyles({
|
||||
container: {
|
||||
position: 'fixed',
|
||||
width: '100%',
|
||||
display: 'flex',
|
||||
zIndex: 10000,
|
||||
top: '20px',
|
||||
justifyContent: "center",
|
||||
alignItems: "center",
|
||||
flexDirection: "column",
|
||||
},
|
||||
message: {
|
||||
width: '100%',
|
||||
maxWidth: '300px',
|
||||
background: '#fafafa', // 浅灰背景与其他状态统一
|
||||
borderRadius: '8px',
|
||||
padding: '10px 10px 10px 20px', // 统一左侧20px留白
|
||||
|
||||
borderLeft: '4px solid #e0e0e0', // 加粗为4px与其他状态一致
|
||||
color: '#757575', // 中性灰文字
|
||||
|
||||
boxShadow: '0 2px 6px rgba(224, 224, 224, 0.15)', // 灰色投影
|
||||
transition: 'all 0.3s ease-in-out', // 补全时间单位
|
||||
|
||||
marginBottom: '20px',
|
||||
|
||||
'&.success': {
|
||||
color: '#2e7d32',
|
||||
backgroundColor: '#f0f9eb',
|
||||
borderLeft: '4px solid #4CAF50',
|
||||
paddingLeft: '20px',
|
||||
boxShadow: '0 2px 6px rgba(76, 175, 80, 0.15)'
|
||||
},
|
||||
'&.warning': {
|
||||
color: '#faad14', // 警告文字色
|
||||
backgroundColor: '#fffbe6', // 浅黄色背景
|
||||
borderLeft: '4px solid #ffc53d', // 琥珀色左侧标识
|
||||
paddingLeft: '20px',
|
||||
boxShadow: '0 2px 6px rgba(255, 197, 61, 0.15)' // 金色投影
|
||||
},
|
||||
'&.error': {
|
||||
color: '#f5222d', // 错误文字色
|
||||
backgroundColor: '#fff1f0', // 浅红色背景
|
||||
borderLeft: '4px solid #ff4d4f', // 品红色左侧标识
|
||||
paddingLeft: '20px',
|
||||
boxShadow: '0 2px 6px rgba(255, 77, 79, 0.15)' // 红色投影
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
let el = document.querySelector("#u-message")
|
||||
if (!el) {
|
||||
el = document.createElement('div')
|
||||
el.className = 'u-message'
|
||||
el.id = 'u-message'
|
||||
document.body.append(el)
|
||||
}
|
||||
|
||||
export interface Message {
|
||||
id: number
|
||||
content: string
|
||||
duration: number
|
||||
type: 'info' | 'success' | 'warning' | 'error'
|
||||
}
|
||||
|
||||
export interface MessageApi {
|
||||
info: (content: string, duration?: number) => void;
|
||||
warning: (content: string, duration?: number) => void;
|
||||
success: (content: string, duration?: number) => void;
|
||||
error: (content: string, duration?: number) => void;
|
||||
}
|
||||
|
||||
const default_duration = 3000
|
||||
|
||||
|
||||
let add: (msg: Message) => void;
|
||||
|
||||
const MessageContainer: React.FC = () => {
|
||||
const classes = useStyle()
|
||||
const [msgs, setMsgs] = useState<Message[]>([]);
|
||||
|
||||
const remove = (id: number) => {
|
||||
setMsgs(prevMsgs => prevMsgs.filter(v => v.id !== id));
|
||||
}
|
||||
|
||||
add = (msg: Message) => {
|
||||
const id = Date.now();
|
||||
setMsgs(prevMsgs => {
|
||||
const newMsgs = [{...msg, id}, ...prevMsgs];
|
||||
// 直接限制数组长度为5,移除最旧的消息(最后一项)
|
||||
if (newMsgs.length > 5) {
|
||||
newMsgs.pop();
|
||||
}
|
||||
return newMsgs;
|
||||
});
|
||||
|
||||
setTimeout(() => {
|
||||
remove(id);
|
||||
}, msg.duration ?? default_duration);
|
||||
}
|
||||
|
||||
return <div className={classes.container}>
|
||||
{msgs.map(m => <div key={m.id} className={`${classes.message} ${m.type}`}>{m.content}</div>)}
|
||||
</div>
|
||||
}
|
||||
|
||||
createRoot(el).render(<MessageContainer/>)
|
||||
|
||||
export const message: MessageApi = {
|
||||
info: function (content: string, duration?: number): void {
|
||||
add({content: content, duration: duration, type: "info"} as Message)
|
||||
},
|
||||
warning: function (content: string, duration?: number): void {
|
||||
add({content: content, duration: duration, type: "warning"} as Message)
|
||||
},
|
||||
success: function (content: string, duration?: number): void {
|
||||
add({content: content, duration: duration, type: "success"} as Message)
|
||||
},
|
||||
error: function (content: string, duration?: number): void {
|
||||
add({content: content, duration: duration, type: "error"} as Message)
|
||||
}
|
||||
}
|
143
frontend/src/page/component/panel-left.tsx
Normal file
143
frontend/src/page/component/panel-left.tsx
Normal file
@ -0,0 +1,143 @@
|
||||
import {createUseStyles} from "react-jss";
|
||||
import {UButton} from "../../component/button/u-button.tsx";
|
||||
import React from "react";
|
||||
import {useStore} from "../../store/share.ts";
|
||||
import {message} from "../../component/message/u-message.tsx";
|
||||
|
||||
const useStyle = createUseStyles({
|
||||
container: {
|
||||
backgroundColor: "#e3f2fd",
|
||||
display: "flex",
|
||||
justifyContent: "center",
|
||||
alignItems: "center",
|
||||
},
|
||||
form: {
|
||||
backgroundColor: "#C8E6C9",
|
||||
boxShadow: "inset 0 0 15px rgba(56, 142, 60, 0.15)",
|
||||
padding: "30px",
|
||||
borderRadius: "15px",
|
||||
width: "70%",
|
||||
margin: "20px 60px 20px 0",
|
||||
/*todo margin 不用 px*/
|
||||
},
|
||||
title: {
|
||||
color: "#2c9678"
|
||||
},
|
||||
file: {
|
||||
display: 'none',
|
||||
},
|
||||
preview: {
|
||||
marginTop: '10px',
|
||||
display: 'flex',
|
||||
},
|
||||
name: {
|
||||
color: "#2c9678",
|
||||
marginLeft: '10px'
|
||||
},
|
||||
clean: {
|
||||
borderRadius: '50%',
|
||||
cursor: 'pointer',
|
||||
'&:hover': {}
|
||||
}
|
||||
})
|
||||
|
||||
interface RespNew {
|
||||
code: string
|
||||
}
|
||||
|
||||
export const PanelLeft = () => {
|
||||
const style = useStyle()
|
||||
const {file, setFile} = useStore()
|
||||
|
||||
function onFileSelect() {
|
||||
// @ts-ignore
|
||||
document.querySelector('#real-file-input').click();
|
||||
}
|
||||
|
||||
function onFileChange(e: React.ChangeEvent<HTMLInputElement>) {
|
||||
console.log('[D] onFileChange: e =', e)
|
||||
setFile(e.currentTarget.files ? e.currentTarget.files[0] : null)
|
||||
}
|
||||
|
||||
async function onFileUpload() {
|
||||
if (!file) {
|
||||
return
|
||||
}
|
||||
|
||||
console.log(`[D] onFileUpload: upload file = ${file.name}, size = ${file.size}`, file)
|
||||
|
||||
let res1 = await fetch(`/api/share/${file.name}`, {
|
||||
method: "PUT",
|
||||
headers: {"X-File-Size": file.size.toString()}
|
||||
})
|
||||
let j1 = await res1.json() as RespNew
|
||||
console.log('[D] onFileUpload: json 1 =', j1)
|
||||
if (!j1.code) {
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
// todo: for 循环上传文件分片直到上传完成
|
||||
|
||||
// 2. 分片上传配置
|
||||
const CHUNK_SIZE = 1024 * 1024 // 1MB分片
|
||||
const totalChunks = Math.ceil(file.size / CHUNK_SIZE)
|
||||
const code = j1.code
|
||||
|
||||
// 3. 循环上传所有分片
|
||||
for (let chunkIndex = 0; chunkIndex < totalChunks; chunkIndex++) {
|
||||
const start = chunkIndex * CHUNK_SIZE
|
||||
const end = Math.min(start + CHUNK_SIZE, file.size)
|
||||
const chunk = file.slice(start, end)
|
||||
|
||||
// 4. 构造Range头(bytes=start-end)
|
||||
const rangeHeader = `bytes=${start}-${end - 1}` // end-1因为Range是闭区间
|
||||
|
||||
// 5. 上传分片
|
||||
const res = await fetch(`/api/share/${code}`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Range": rangeHeader,
|
||||
"Content-Type": "application/octet-stream" // 二进制流类型
|
||||
},
|
||||
body: chunk
|
||||
})
|
||||
|
||||
if (!res.ok) {
|
||||
const err = await res.text()
|
||||
throw new Error(`分片 ${chunkIndex} 上传失败: ${err}`)
|
||||
}
|
||||
|
||||
console.log(`[D] 分片进度: ${chunkIndex + 1}/${totalChunks}`,
|
||||
`(${Math.round((chunkIndex + 1)/totalChunks*100)}%)`)
|
||||
}
|
||||
|
||||
console.log('[D] 所有分片上传完成')
|
||||
}
|
||||
|
||||
function onFileClean() {
|
||||
setFile(null)
|
||||
}
|
||||
|
||||
return <div className={style.container}>
|
||||
<div className={style.form}>
|
||||
<h2 className={style.title}>上传文件</h2>
|
||||
{
|
||||
!file &&
|
||||
<UButton onClick={onFileSelect}>选择文件</UButton>
|
||||
}
|
||||
{
|
||||
file &&
|
||||
<UButton onClick={onFileUpload}>上传文件</UButton>
|
||||
}
|
||||
<input type="file" className={style.file} id="real-file-input" onChange={onFileChange}/>
|
||||
{
|
||||
file &&
|
||||
<div className={style.preview}>
|
||||
<div className={style.clean} onClick={onFileClean}>×</div>
|
||||
<div className={style.name}>{file.name}</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
};
|
29
frontend/src/page/component/panel-mid.tsx
Normal file
29
frontend/src/page/component/panel-mid.tsx
Normal file
@ -0,0 +1,29 @@
|
||||
import {createUseStyles} from "react-jss";
|
||||
|
||||
const useStyle = createUseStyles({
|
||||
container: {
|
||||
position: "relative",
|
||||
overflow: "hidden",
|
||||
},
|
||||
left: {
|
||||
backgroundColor: "#e3f2fd",
|
||||
position: "absolute",
|
||||
width: "100%",
|
||||
height: "100%",
|
||||
clipPath: 'polygon(0 0, 100% 0, 0 100%)'
|
||||
},
|
||||
right: {
|
||||
backgroundColor: "#e8f5e9",
|
||||
position: "absolute",
|
||||
width: "100%",
|
||||
height: "100%",
|
||||
clipPath: 'polygon(100% 0, 100% 100%, 0 100%)'
|
||||
},
|
||||
})
|
||||
export const PanelMid = () => {
|
||||
const style = useStyle()
|
||||
return <div className={style.container}>
|
||||
<div className={style.left}></div>
|
||||
<div className={style.right}></div>
|
||||
</div>
|
||||
};
|
68
frontend/src/page/component/panel-right.tsx
Normal file
68
frontend/src/page/component/panel-right.tsx
Normal file
@ -0,0 +1,68 @@
|
||||
import {createUseStyles} from "react-jss";
|
||||
import {UButton} from "../../component/button/u-button.tsx";
|
||||
import {useStore} from "../../store/share.ts";
|
||||
|
||||
const useStyle = createUseStyles({
|
||||
container: {
|
||||
backgroundColor: "#e8f5e9",
|
||||
display: "flex",
|
||||
justifyContent: "center",
|
||||
alignItems: "center",
|
||||
},
|
||||
form: {
|
||||
backgroundColor: "#BBDEFB",
|
||||
boxShadow: "inset 0 0 15px rgba(33, 150, 243, 0.15)",
|
||||
padding: "30px",
|
||||
borderRadius: "15px",
|
||||
width: "70%",
|
||||
margin: "20px 0 20px 60px",
|
||||
/*todo margin 不用 px*/
|
||||
},
|
||||
title: {
|
||||
color: '#1661ab', // 靛青
|
||||
},
|
||||
code: {
|
||||
padding: '11px',
|
||||
margin: '20px 0',
|
||||
width: '200px',
|
||||
border: '2px solid #ddd',
|
||||
borderRadius: '5px',
|
||||
'&:active': {
|
||||
border: '2px solid #1661ab',
|
||||
}
|
||||
}
|
||||
})
|
||||
export const PanelRight = () => {
|
||||
const style = useStyle()
|
||||
const {code, setCode} = useStore()
|
||||
|
||||
function onCodeChange(e: React.ChangeEvent<HTMLInputElement>) {
|
||||
setCode(e.currentTarget.value)
|
||||
}
|
||||
|
||||
async function onFetchFile() {
|
||||
const url = `/api/share/${code}`
|
||||
console.log('[D] onFetchFile: url =', url)
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
}
|
||||
|
||||
return <div className={style.container}>
|
||||
<div className={style.form}>
|
||||
<h2 className={style.title}>获取文件</h2>
|
||||
<div>
|
||||
<input
|
||||
type="text"
|
||||
className={style.code}
|
||||
placeholder="输入下载码"
|
||||
value={code}
|
||||
onChange={onCodeChange}
|
||||
/>
|
||||
<UButton style={{marginLeft: '10px'}} onClick={onFetchFile}>获取文件</UButton>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
};
|
@ -1,15 +0,0 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
.mid-left {
|
||||
background-color: #e3f2fd; /* 柔和的浅蓝色 */
|
||||
}
|
||||
.mid-right {
|
||||
background-color: #e8f5e9; /* 柔和的浅绿色 */
|
||||
}
|
||||
|
||||
.share-left {
|
||||
background-color: #e3f2fd; /* 柔和的浅蓝色 */
|
||||
}
|
||||
.share-right {
|
||||
background-color: #e8f5e9;
|
||||
}
|
@ -1,130 +1,26 @@
|
||||
import "./share.css";
|
||||
// FileSharing.tsx
|
||||
import { useRef, useState } from 'react';
|
||||
import {createUseStyles} from 'react-jss'
|
||||
import {PanelLeft} from "./component/panel-left.tsx";
|
||||
import {PanelRight} from "./component/panel-right.tsx";
|
||||
import {PanelMid} from "./component/panel-mid.tsx";
|
||||
|
||||
type FileItemProps = {
|
||||
fileName: string;
|
||||
onClear: () => void;
|
||||
};
|
||||
const useStyle = createUseStyles({
|
||||
"@global": {
|
||||
margin: 0,
|
||||
padding: 0,
|
||||
},
|
||||
container: {
|
||||
margin: 0,
|
||||
height: "100vh",
|
||||
display: "grid",
|
||||
gridTemplateColumns: "40% 20% 40%",
|
||||
},
|
||||
})
|
||||
|
||||
const FileItem = ({ fileName, onClear }: FileItemProps) => (
|
||||
<div className="flex items-center gap-2 my-2">
|
||||
<button
|
||||
className="w-5 h-5 rounded-full flex items-center justify-center text-white hover:bg-red-400 transition-colors"
|
||||
onClick={onClear}
|
||||
>
|
||||
×
|
||||
</button>
|
||||
<span className="text-gray-700">{fileName}</span>
|
||||
export const FileSharing = () => {
|
||||
const style = useStyle()
|
||||
return <div className={style.container}>
|
||||
<PanelLeft />
|
||||
<PanelMid/>
|
||||
<PanelRight/>
|
||||
</div>
|
||||
);
|
||||
|
||||
const MiddlePanel = () => (
|
||||
<div className="relative bg-gray-200 overflow-hidden">
|
||||
<div
|
||||
className="mid-left absolute w-full h-full bg-blue-100"
|
||||
style={{ clipPath: 'polygon(0 0, 100% 0, 0 100%)' }}
|
||||
/>
|
||||
<div
|
||||
className="mid-right absolute w-full h-full bg-green-100"
|
||||
style={{ clipPath: 'polygon(100% 0, 100% 100%, 0 100%)' }}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
const UploadPanel = () => {
|
||||
const [selectedFile, setSelectedFile] = useState<File | null>(null);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const handleFileSelect = () => {
|
||||
if (!selectedFile && fileInputRef.current) {
|
||||
fileInputRef.current.click();
|
||||
} else {
|
||||
// Handle upload logic
|
||||
if (selectedFile) {
|
||||
const formData = new FormData();
|
||||
formData.append('file', selectedFile);
|
||||
|
||||
// Replace with actual API call
|
||||
fetch('https://your-upload-api.com/upload', {
|
||||
method: 'POST',
|
||||
body: formData
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
alert(`Upload success! Code: ${data.code}`);
|
||||
setSelectedFile(null);
|
||||
})
|
||||
.catch(() => alert('Upload failed'));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="share-left flex flex-col items-center justify-center p-5 bg-blue-50 h-full">
|
||||
<div className="bg-blue-100 rounded-xl p-6 w-4/5 shadow-inner">
|
||||
<h2 className="text-xl font-semibold mb-4 text-cyan-900">上传文件</h2>
|
||||
<input
|
||||
type="file"
|
||||
ref={fileInputRef}
|
||||
className="hidden"
|
||||
onChange={(e) => e.target.files?.[0] && setSelectedFile(e.target.files[0])}
|
||||
/>
|
||||
<button
|
||||
onClick={handleFileSelect}
|
||||
className="bg-green-500 text-white px-4 py-2 rounded-lg hover:bg-green-600 transition-colors"
|
||||
>
|
||||
{selectedFile ? '确认上传' : '选择文件'}
|
||||
</button>
|
||||
{selectedFile && (
|
||||
<FileItem
|
||||
fileName={selectedFile.name}
|
||||
onClear={() => setSelectedFile(null)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const DownloadPanel = () => {
|
||||
const [downloadCode, setDownloadCode] = useState('');
|
||||
|
||||
const handleDownload = () => {
|
||||
if (!downloadCode) {
|
||||
alert('请输入下载码');
|
||||
return;
|
||||
}
|
||||
// Replace with actual download logic
|
||||
window.location.href = `https://your-download-api.com/download?code=${downloadCode}`;
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="share-right flex flex-col items-center justify-center p-5 bg-green-50 h-full">
|
||||
<div className="bg-green-100 rounded-xl p-6 w-4/5 shadow-inner">
|
||||
<h2 className="text-xl font-semibold mb-4 text-teal-900">下载文件</h2>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="输入下载码"
|
||||
className="w-full px-3 py-2 border-2 border-gray-200 rounded-lg mb-4"
|
||||
value={downloadCode}
|
||||
onChange={(e) => setDownloadCode(e.target.value)}
|
||||
/>
|
||||
<button
|
||||
onClick={handleDownload}
|
||||
className="bg-green-500 text-white px-4 py-2 rounded-lg hover:bg-green-600 transition-colors w-full"
|
||||
>
|
||||
下载文件
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export const FileSharing = () => (
|
||||
<div className="h-screen grid grid-cols-[40%_20%_40%]">
|
||||
<UploadPanel />
|
||||
<MiddlePanel />
|
||||
<DownloadPanel />
|
||||
</div>
|
||||
);
|
||||
};
|
23
frontend/src/store/share.ts
Normal file
23
frontend/src/store/share.ts
Normal file
@ -0,0 +1,23 @@
|
||||
import {create} from 'zustand'
|
||||
|
||||
type Store = {
|
||||
file: File | null,
|
||||
setFile: (f: File | null) => void
|
||||
code: string,
|
||||
setCode: (value:string) => void
|
||||
}
|
||||
|
||||
export const useStore = create<Store>()((set) => ({
|
||||
file: null,
|
||||
setFile: (f: File | null = null) => {
|
||||
set(state => {
|
||||
return {...state, file: f}
|
||||
})
|
||||
},
|
||||
code: '',
|
||||
setCode: (value:string= '') => {
|
||||
set(state => {
|
||||
return {...state, code: value}
|
||||
})
|
||||
}
|
||||
}))
|
Reference in New Issue
Block a user