Skip to content

Let's use AI to Earn!

空间和分片

daoyian0b49c3c7e0b3
diff --git a/src/api/file.ts b/src/api/file.ts
deleted file mode 100644
index f480b294..00000000
--- a/src/api/file.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-import { request } from "@/utils/request";
-
-export const apiInitiateMultipartUpload = (data: {
- fileName: string;
- secondPath: string;
- fileSize: number;
- contentType: string;
-}) => {
- return request<{
- fileId: string;
- uploadId: string;
- }>({
- url: "/file/uploadPart/init",
- method: "POST",
- data,
- });
-};
-
-export const apiUploadPart = (
- fileId: string,
- uploadId: string,
- partNumber: number,
- file: Blob,
-) => {
- const formData = new FormData();
- formData.append("file", file);
- return request<{
- ETag: string;
- PartNumber: number;
- }>({
- url: "/file/uploadPart/upload",
- method: "POST",
- data: formData,
- params: {
- fileId,
- uploadId,
- partNumber,
- },
- });
-};
-
-export const apiUploadPartComplete = (data: {
- fileId: string;
- uploadId: string;
- parts: { PartNumber: number; ETag: string }[];
-}) => {
- return request({
- url: "/file/uploadPart/complete",
- method: "POST",
- data,
- });
-};
diff --git a/src/api/oss.ts b/src/api/oss.ts
index a85d38b9..c3b49eae 100644
--- a/src/api/oss.ts
+++ b/src/api/oss.ts
@@ -1,9 +1,15 @@
import { request } from "@/utils/request";
// 上传文件到OSS
-export const uploadToOss = async (file: File) => {
+export const uploadToOss = async (file: File, onProgress?: (prog: number) => void) => {
try {
- // 2. 上传文件到OSS
+ console.log("uploadToOss", file.size);
+ // 如果文件大于10MB,使用分片上传
+ if (file.size > (10 * 1024 * 1024)) {
+ return uploadToOssMultipart(file, onProgress);
+ }
+
+ // 小于10MB,使用普通上传
const formData = new FormData();
formData.append("file", file);
@@ -18,3 +24,82 @@ export const uploadToOss = async (file: File) => {
throw error;
}
};
+
+// 分片上传文件到OSS
+export const uploadToOssMultipart = async (file: File, onProgress?: (prog: number) => void) => {
+ try {
+ // 1. 初始化分片上传
+ const initResponse: any = await request({
+ url: "/file/uploadPart/init",
+ method: "POST",
+ data: {
+ fileName: file.name,
+ secondPath: "uploads",
+ fileSize: file.size,
+ contentType: file.type || "application/octet-stream",
+ },
+ });
+
+ if (initResponse.code != 0) {
+ throw new Error("初始化上传失败");
+ }
+
+ const { fileId, uploadId } = initResponse.data;
+
+ // 2. 分片上传文件
+ const chunkSize = 5 * 1024 * 1024; // 5MB per chunk
+ const chunks = Math.ceil(file.size / chunkSize);
+ const parts = [];
+
+ for (let i = 0; i < chunks; i++) {
+ const start = i * chunkSize;
+ const end = Math.min(start + chunkSize, file.size);
+ const chunk = file.slice(start, end);
+
+ // 上传分片
+ const formData = new FormData();
+ formData.append("file", chunk);
+
+ const partResponse: any = await request({
+ url: "/file/uploadPart/upload",
+ method: "POST",
+ data: formData,
+ params: {
+ fileId,
+ uploadId,
+ partNumber: i + 1,
+ },
+ });
+
+ if (partResponse.code != 0) {
+ throw new Error("分片上传失败");
+ }
+
+ parts.push({
+ PartNumber: partResponse.data.PartNumber,
+ ETag: partResponse.data.ETag,
+ });
+
+ // 更新进度
+ const currentProgress = Math.round(((i + 1) / chunks) * 100);
+ if (onProgress) onProgress(currentProgress);
+ }
+
+ // 3. 完成分片上传
+ await request({
+ url: "/file/uploadPart/complete",
+ method: "POST",
+ data: {
+ fileId,
+ uploadId,
+ parts,
+ },
+ });
+
+ // 文件地址在初始化时就已经返回了
+ return fileId;
+ } catch (error) {
+ console.error("分片上传失败:", error);
+ throw error;
+ }
+};
diff --git a/src/api/tools.ts b/src/api/tools.ts
index 3e04c1d8..91db810b 100644
--- a/src/api/tools.ts
+++ b/src/api/tools.ts
@@ -97,6 +97,16 @@ export const toolsApi = {
file: Blob,
onProgress?: (prog: number) => void,
): Promise<string> {
+ const fileSize = file.size;
+ const fileName = (file as any).name || 'file';
+ const contentType = file.type || 'application/octet-stream';
+
+ // 如果文件大于10MB,使用分片上传
+ if (fileSize > (10 * 1024 * 1024)) {
+ return this.uploadFileTempMultipart(file, fileName, contentType, onProgress);
+ }
+
+ // 小于10MB,使用普通上传
const formData = new FormData();
formData.append("file", file);
@@ -117,6 +127,94 @@ export const toolsApi = {
return res.data.data.key;
},
+ /**
+ * 分片上传文件临时
+ */
+ async uploadFileTempMultipart(
+ file: Blob,
+ fileName: string,
+ contentType: string,
+ onProgress?: (prog: number) => void,
+ ): Promise<string> {
+ try {
+ // 1. 初始化分片上传
+ const initResponse = await axios({
+ url: `${process.env.NEXT_PUBLIC_API_URL_PROXY}/file/uploadPart/init`,
+ method: "POST",
+ data: {
+ fileName,
+ secondPath: "uploads",
+ fileSize: file.size,
+ contentType,
+ },
+ });
+
+ if (initResponse.data.code != 0) {
+ throw new Error("初始化上传失败");
+ }
+
+ const { fileId, uploadId } = initResponse.data.data;
+ console.log("初始化分片上传成功:", fileId, uploadId);
+
+ // 2. 分片上传文件
+ const chunkSize = 5 * 1024 * 1024; // 5MB per chunk
+ const chunks = Math.ceil(file.size / chunkSize);
+ const parts = [];
+
+ for (let i = 0; i < chunks; i++) {
+ const start = i * chunkSize;
+ const end = Math.min(start + chunkSize, file.size);
+ const chunk = file.slice(start, end);
+
+ // 上传分片
+ const formData = new FormData();
+ formData.append("file", chunk);
+
+ const partResponse = await axios({
+ url: `${process.env.NEXT_PUBLIC_API_URL_PROXY}/file/uploadPart/upload`,
+ method: "POST",
+ data: formData,
+ params: {
+ fileId,
+ uploadId,
+ partNumber: i + 1,
+ },
+ });
+
+ if (partResponse.data.code != 0) {
+ throw new Error("分片上传失败");
+ }
+
+ parts.push({
+ PartNumber: partResponse.data.data.PartNumber,
+ ETag: partResponse.data.data.ETag,
+ });
+
+ // 更新进度
+ const currentProgress = Math.round(((i + 1) / chunks) * 100);
+ if (onProgress) onProgress(currentProgress);
+ console.log(`分片 ${i + 1}/${chunks} 上传完成`);
+ }
+
+ // 3. 完成分片上传
+ await axios({
+ url: `${process.env.NEXT_PUBLIC_API_URL_PROXY}/file/uploadPart/complete`,
+ method: "POST",
+ data: {
+ fileId,
+ uploadId,
+ parts,
+ },
+ });
+
+ // 文件地址在初始化时就已经返回了
+ return fileId;
+ } catch (error) {
+ console.error("分片上传失败:", error);
+ throw error;
+ }
+ },
+
/**
* 文本内容安全
*/
diff --git a/src/app/[lng]/accounts/components/AccountSidebar/UserManageSidebar.tsx b/src/app/[lng]/accounts/components/AccountSidebar/UserManageSidebar.tsx
index 299acc97..626accf2 100644
--- a/src/app/[lng]/accounts/components/AccountSidebar/UserManageSidebar.tsx
+++ b/src/app/[lng]/accounts/components/AccountSidebar/UserManageSidebar.tsx
@@ -129,7 +129,7 @@ const UserManageSidebar = memo(
</ControlledMenu>
<Modal
- title={createGroupId === "-1" ? "新建列表" : "重命名列表"}
+ title={createGroupId === "-1" ? "新建空间" : "重命名空间"}
open={openCreateGroup}
onCancel={createGroupCancel}
footer={
@@ -163,10 +163,10 @@ const UserManageSidebar = memo(
}
>
<div className={styles.createGroup}>
- <label>列表名</label>
+ <label>空间名</label>
<Input
value={groupName}
- placeholder="请输入列表名称"
+ placeholder="请输入空间名称"
onChange={(e) => setGroupName(e.target.value)}
/>
</div>
@@ -189,7 +189,7 @@ const UserManageSidebar = memo(
</span>
</div>
<div className="userManage-sidebar-list">
- <p className="userManage-sidebar-list-title">列表</p>
+ <p className="userManage-sidebar-list-title">空间</p>
<ReactSortable
className="userManage-sidebar-list-sortable"
@@ -252,7 +252,7 @@ const UserManageSidebar = memo(
setOpenCreateGroup(true);
}}
>
- 新建列表
+ 新建空间
</Button>
</div>
</div>
diff --git a/src/app/[lng]/demo/demoFile.tsx b/src/app/[lng]/demo/demoFile.tsx
deleted file mode 100644
index 5d7d74e2..00000000
--- a/src/app/[lng]/demo/demoFile.tsx
+++ /dev/null
@@ -1,164 +0,0 @@
-"use client";
-
-import React, { useState } from "react";
-import {
- apiInitiateMultipartUpload,
- apiUploadPart,
- apiUploadPartComplete,
-} from "@/api/file";
-
-export const DemoFile = () => {
- const [file, setFile] = useState<File | null>(null);
- const [uploading, setUploading] = useState(false);
- const [progress, setProgress] = useState(0);
- const [uploadedParts, setUploadedParts] = useState<
- { PartNumber: number; ETag: string }[]
- >([]);
-
- const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
- if (e.target.files && e.target.files[0]) {
- setFile(e.target.files[0]);
- }
- };
-
- const handleUpload = async () => {
- if (!file) return;
-
- setUploading(true);
- setProgress(0);
- setUploadedParts([]);
-
- try {
- // 1. 初始化分片上传
- const initResponse = await apiInitiateMultipartUpload({
- fileName: file.name,
- secondPath: "uploads", // 根据需要调整路径
- fileSize: file.size,
- contentType: file.type || "application/octet-stream",
- });
- if (!initResponse) {
- throw new Error("初始化上传失败");
- }
-
- const { fileId, uploadId } = initResponse.data;
- console.log("初始化上传成功:", fileId, uploadId);
-
- // 2. 分片上传文件
- const chunkSize = 5 * 1024 * 1024; // 5MB per chunk
- const chunks = Math.ceil(file.size / chunkSize);
- const parts = [];
-
- for (let i = 0; i < chunks; i++) {
- const start = i * chunkSize;
- const end = Math.min(start + chunkSize, file.size);
- const chunk = file.slice(start, end);
-
- // 上传分片
- const partResponse = await apiUploadPart(
- fileId,
- uploadId,
- i + 1,
- chunk,
- );
- if (!partResponse) {
- throw new Error("分片上传失败");
- }
-
- parts.push({
- PartNumber: partResponse.data.PartNumber,
- ETag: partResponse.data.ETag,
- });
-
- // 更新进度
- const currentProgress = Math.round(((i + 1) / chunks) * 100);
- setProgress(currentProgress);
- console.log(`分片 ${i + 1}/${chunks} 上传完成`);
- }
-
- setUploadedParts(parts);
-
- // 3. 完成分片上传
- await apiUploadPartComplete({
- fileId: fileId,
- uploadId,
- parts,
- });
-
- alert("文件上传成功!");
- } catch (error) {
- console.error("文件上传失败:", error);
- alert("文件上传失败!");
- } finally {
- setUploading(false);
- setProgress(0);
- }
- };
-
- return (
- <div className="p-4 max-w-2xl mx-auto">
- <h2 className="text-2xl font-bold mb-6">分片文件上传</h2>
-
- <div className="mb-6">
- <label className="block mb-2 text-sm font-medium text-gray-700">
- 选择文件
- </label>
- <input
- type="file"
- onChange={handleFileChange}
- disabled={uploading}
- className="block w-full text-sm text-gray-500
- file:mr-4 file:py-2 file:px-4
- file:rounded file:border-0
- file:text-sm file:font-semibold
- file:bg-blue-50 file:text-blue-700
- hover:file:bg-blue-100"
- />
- </div>
-
- {file && (
- <div className="mb-6 p-4 bg-gray-50 rounded-lg">
- <h3 className="font-medium mb-2">文件信息:</h3>
- <p>
- <span className="font-medium">文件名:</span> {file.name}
- </p>
- <p>
- <span className="font-medium">文件大小:</span>{" "}
- {Math.round(file.size / 1024)} KB
- </p>
- <p>
- <span className="font-medium">文件类型:</span> {file.type || "未知"}
- </p>
- </div>
- )}
-
- <button
- onClick={handleUpload}
- disabled={!file || uploading}
- className="px-6 py-2 bg-blue-600 text-white rounded-lg disabled:bg-gray-400 hover:bg-blue-700 transition-colors"
- >
- {uploading ? "上传中..." : "开始上传"}
- </button>
-
- {uploading && (
- <div className="mt-6">
- <div className="flex justify-between mb-1">
- <span className="text-sm font-medium">上传进度</span>
- <span className="text-sm font-medium">{progress}%</span>
- </div>
- <div className="w-full bg-gray-200 rounded-full h-2.5">
- <div
- className="bg-blue-600 h-2.5 rounded-full transition-all duration-300"
- style={{ width: `${progress}%` }}
- ></div>
- </div>
-
- {uploadedParts.length > 0 && (
- <div className="mt-4 text-sm text-gray-600">
- 已完成 {uploadedParts.length} 个分片上传
- </div>
- )}
- </div>
- )}
- </div>
- );
-};
diff --git a/src/app/[lng]/demo/page.tsx b/src/app/[lng]/demo/page.tsx
index c501cd46..e0f0d1b5 100644
--- a/src/app/[lng]/demo/page.tsx
+++ b/src/app/[lng]/demo/page.tsx
@@ -7,7 +7,6 @@ import { DemoPublish } from "@/app/[lng]/demo/demoPublish";
import { DemoMaterial } from "@/app/[lng]/demo/demoMaterial";
import { DemoData } from "./demoData";
import { DemoInteract } from "./demoInteract";
-import { DemoFile } from "./demoFile";
export async function generateMetadata({ params }: PageParams) {
const { lng } = await params;
@@ -32,7 +31,6 @@ export default async function Page({ params }: PageParams) {
<DemoMaterial />
<DemoData />
<DemoInteract />
- <DemoFile />
</>
);
}
diff --git a/src/app/[lng]/demo/uploadExample.tsx b/src/app/[lng]/demo/uploadExample.tsx
new file mode 100644
index 00000000..3a89761b
--- /dev/null
+++ b/src/app/[lng]/demo/uploadExample.tsx
@@ -0,0 +1,168 @@
+"use client";
+
+import React, { useState } from "react";
+import { uploadToOss } from "@/api/oss";
+import { tools } from "@/api/tools";
+
+export const UploadExample = () => {
+ const [file, setFile] = useState<File | null>(null);
+ const [uploading, setUploading] = useState(false);
+ const [progress, setProgress] = useState(0);
+ const [uploadType, setUploadType] = useState<'oss' | 'temp'>('oss');
+ const [result, setResult] = useState<string>('');
+
+ const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
+ if (e.target.files && e.target.files[0]) {
+ setFile(e.target.files[0]);
+ setResult('');
+ }
+ };
+
+ const handleUpload = async () => {
+ if (!file) return;
+
+ setUploading(true);
+ setProgress(0);
+ setResult('');
+
+ try {
+ let key: string;
+
+ if (uploadType === 'oss') {
+ // 使用 uploadToOss
+ key = await uploadToOss(file, (prog) => {
+ setProgress(prog);
+ });
+ } else {
+ // 使用 uploadFileTemp
+ key = await tools.uploadFileTemp(file, (prog) => {
+ setProgress(prog);
+ });
+ }
+
+ setResult(`上传成功!文件Key: ${key}`);
+ console.log('上传成功:', key);
+ } catch (error) {
+ console.error("上传失败:", error);
+ setResult(`上传失败: ${error instanceof Error ? error.message : '未知错误'}`);
+ } finally {
+ setUploading(false);
+ }
+ };
+
+ const formatFileSize = (bytes: number) => {
+ if (bytes === 0) return '0 Bytes';
+ const k = 1024;
+ const sizes = ['Bytes', 'KB', 'MB', 'GB'];
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
+ return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
+ };
+
+ return (
+ <div className="p-6 max-w-2xl mx-auto">
+ <h2 className="text-2xl font-bold mb-6">文件上传示例</h2>
+
+ <div className="mb-6">
+ <label className="block mb-2 text-sm font-medium text-gray-700">
+ 选择上传类型
+ </label>
+ <div className="flex gap-4">
+ <label className="flex items-center">
+ <input
+ type="radio"
+ value="oss"
+ checked={uploadType === 'oss'}
+ onChange={(e) => setUploadType(e.target.value as 'oss')}
+ className="mr-2"
+ />
+ OSS上传
+ </label>
+ <label className="flex items-center">
+ <input
+ type="radio"
+ value="temp"
+ checked={uploadType === 'temp'}
+ onChange={(e) => setUploadType(e.target.value as 'temp')}
+ className="mr-2"
+ />
+ 临时上传
+ </label>
+ </div>
+ </div>
+
+ <div className="mb-6">
+ <label className="block mb-2 text-sm font-medium text-gray-700">
+ 选择文件
+ </label>
+ <input
+ type="file"
+ onChange={handleFileChange}
+ disabled={uploading}
+ className="block w-full text-sm text-gray-500
+ file:mr-4 file:py-2 file:px-4
+ file:rounded file:border-0
+ file:text-sm file:font-semibold
+ file:bg-blue-50 file:text-blue-700
+ hover:file:bg-blue-100"
+ />
+ </div>
+
+ {file && (
+ <div className="mb-6 p-4 bg-gray-50 rounded-lg">
+ <h3 className="font-medium mb-2">文件信息:</h3>
+ <p><span className="font-medium">文件名:</span> {file.name}</p>
+ <p><span className="font-medium">文件大小:</span> {formatFileSize(file.size)}</p>
+ <p><span className="font-medium">文件类型:</span> {file.type || "未知"}</p>
+ <p className="mt-2 text-sm text-gray-600">
+ {file.size > 10 * 1024 * 1024
+ ? "⚠️ 文件大于10MB,将使用分片上传"
+ : "✅ 文件小于10MB,将使用普通上传"}
+ </p>
+ </div>
+ )}
+
+ <button
+ onClick={handleUpload}
+ disabled={!file || uploading}
+ className="px-6 py-2 bg-blue-600 text-white rounded-lg disabled:bg-gray-400 hover:bg-blue-700 transition-colors"
+ >
+ {uploading ? "上传中..." : "开始上传"}
+ </button>
+
+ {uploading && (
+ <div className="mt-6">
+ <div className="flex justify-between mb-1">
+ <span className="text-sm font-medium">上传进度</span>
+ <span className="text-sm font-medium">{progress}%</span>
+ </div>
+ <div className="w-full bg-gray-200 rounded-full h-2.5">
+ <div
+ className="bg-blue-600 h-2.5 rounded-full transition-all duration-300"
+ style={{ width: `${progress}%` }}
+ ></div>
+ </div>
+ </div>
+ )}
+
+ {result && (
+ <div className={`mt-6 p-4 rounded-lg ${
+ result.includes('成功')
+ ? 'bg-green-50 text-green-800 border border-green-200'
+ : 'bg-red-50 text-red-800 border border-red-200'
+ }`}>
+ <p className="font-medium">{result}</p>
+ </div>
+ )}
+
+ <div className="mt-8 p-4 bg-blue-50 rounded-lg">
+ <h3 className="font-medium mb-2 text-blue-800">功能说明:</h3>
+ <ul className="text-sm text-blue-700 space-y-1">
+ <li>• 文件小于10MB:使用普通上传</li>
+ <li>• 文件大于10MB:自动使用分片上传(5MB/片)</li>
+ <li>• 支持进度回调,实时显示上传进度</li>
+ <li>• 支持OSS上传和临时上传两种方式</li>
+ </ul>
+ </div>
+ </div>
+ );
+};
diff --git a/src/app/[lng]/material/album/[id]/page.tsx b/src/app/[lng]/material/album/[id]/page.tsx
index 7454f5d9..c21b7f01 100644
--- a/src/app/[lng]/material/album/[id]/page.tsx
+++ b/src/app/[lng]/material/album/[id]/page.tsx
@@ -30,7 +30,6 @@ export default function AlbumPage() {
const router = useRouter();
const searchParams = useSearchParams();
const albumId = params.id as string;
- console.log('idzhi id', albumId)
const [mediaList, setMediaList] = useState<Media[]>([]);
const [groupInfo, setGroupInfo] = useState<MediaGroup | null>(null);