Bỏ qua để đến nội dung chính

Tải lên theo khối

Tải lên tệp lớn bằng cách chia chúng thành các khối nhỏ hơn. Điều này cho phép:

  • Tải lên tệp lớn hơn giới hạn máy chủ
  • Tải lên có thể tiếp tục sau khi mạng bị lỗi
  • Theo dõi tiến trình tốt hơn
  • Giảm sử dụng bộ nhớ

Tải lên theo khối cơ bản

import { useDropup, createChunkedUploader } from '@samithahansaka/dropup';

function ChunkedUploader() {
const { files, actions, state, getDropProps, getInputProps } = useDropup({
upload: createChunkedUploader({
url: '/api/upload/chunk',
chunkSize: 5 * 1024 * 1024, // Khối 5MB
}),
});

return (
<div>
<div {...getDropProps()} style={styles.dropzone}>
<input {...getInputProps()} />
<p>Thả tệp lớn vào đây - chúng sẽ được tải lên theo khối</p>
</div>

{files.map(file => (
<div key={file.id} style={styles.fileItem}>
<span>{file.name}</span>
<span>{(file.size / 1024 / 1024).toFixed(1)} MB</span>

{file.status === 'uploading' && (
<div style={styles.progressBar}>
<div
style={{
...styles.progress,
width: `${file.progress}%`,
}}
/>
</div>
)}

<span>{file.status}</span>
</div>
))}

<button
onClick={() => actions.upload()}
disabled={state.isUploading}
>
Tải lên
</button>
</div>
);
}

const styles = {
dropzone: {
border: '2px dashed #ccc',
borderRadius: 8,
padding: 40,
textAlign: 'center' as const,
marginBottom: 20,
},
fileItem: {
display: 'flex',
alignItems: 'center',
gap: 12,
padding: 12,
borderBottom: '1px solid #eee',
},
progressBar: {
flex: 1,
height: 8,
backgroundColor: '#eee',
borderRadius: 4,
overflow: 'hidden',
},
progress: {
height: '100%',
backgroundColor: '#4caf50',
transition: 'width 0.2s',
},
};

Tùy chọn tải lên theo khối

createChunkedUploader({
// Bắt buộc
url: '/api/upload/chunk',

// Cài đặt tùy chọn
chunkSize: 5 * 1024 * 1024, // 5MB (mặc định)
concurrency: 3, // Khối song song (mặc định: 1)
retries: 3, // Thử lại khối thất bại (mặc định: 3)

// Headers cho tất cả yêu cầu khối
headers: {
'Authorization': 'Bearer token',
},

// Metadata khối tùy chỉnh
getChunkMeta: (file, chunkIndex, totalChunks) => ({
fileId: file.id,
fileName: file.name,
chunkIndex,
totalChunks,
}),
});

Xử lý phía máy chủ

Máy chủ của bạn cần xử lý tải lên theo khối và ghép lại chúng.

Ví dụ: Node.js/Express

const express = require('express');
const multer = require('multer');
const fs = require('fs');
const path = require('path');

const app = express();
const upload = multer({ dest: 'chunks/' });

const uploadState = new Map();

app.post('/api/upload/chunk', upload.single('chunk'), (req, res) => {
const { fileId, fileName, chunkIndex, totalChunks } = req.body;

// Lưu thông tin khối
if (!uploadState.has(fileId)) {
uploadState.set(fileId, {
fileName,
totalChunks: parseInt(totalChunks),
chunks: [],
});
}

const state = uploadState.get(fileId);
state.chunks.push({
index: parseInt(chunkIndex),
path: req.file.path,
});

// Kiểm tra nếu tất cả khối đã nhận
if (state.chunks.length === state.totalChunks) {
// Sắp xếp khối theo index
state.chunks.sort((a, b) => a.index - b.index);

// Ghép các khối
const finalPath = path.join('uploads', fileName);
const writeStream = fs.createWriteStream(finalPath);

for (const chunk of state.chunks) {
const data = fs.readFileSync(chunk.path);
writeStream.write(data);
fs.unlinkSync(chunk.path); // Dọn dẹp khối
}

writeStream.end();
uploadState.delete(fileId);

return res.json({
complete: true,
url: `/uploads/${fileName}`,
});
}

res.json({
complete: false,
received: state.chunks.length,
total: state.totalChunks,
});
});

Giao thức tus

Để tải lên có thể tiếp tục mạnh mẽ, sử dụng giao thức tus:

import { useDropup } from '@samithahansaka/dropup';
import { createTusUploader } from '@samithahansaka/dropup/tus';

function TusUploader() {
const { files, actions, state, getDropProps, getInputProps } = useDropup({
upload: createTusUploader({
endpoint: 'https://tusd.tusdemo.net/files/',

// Cài đặt tùy chọn
chunkSize: 5 * 1024 * 1024,
retryDelays: [0, 1000, 3000, 5000],

// Metadata cho máy chủ
metadata: {
filetype: 'file.type',
filename: 'file.name',
},

// Tiếp tục từ localStorage
storeFingerprintForResuming: true,
}),

onUploadComplete: (file) => {
console.log('Tải lên tus hoàn thành:', file.uploadedUrl);
},
});

return (
<div>
<div {...getDropProps()} style={styles.dropzone}>
<input {...getInputProps()} />
<p>Thả tệp để tải lên có thể tiếp tục</p>
</div>

{files.map(file => (
<div key={file.id} style={styles.fileItem}>
<span>{file.name}</span>
<span>{file.progress}%</span>
<span>{file.status}</span>
</div>
))}

<button onClick={() => actions.upload()}>
Tải lên
</button>
</div>
);
}

Tạm dừng và tiếp tục

Với tải lên theo khối, bạn có thể tạm dừng và tiếp tục:

function PausableUploader() {
const { files, actions, getDropProps, getInputProps } = useDropup({
upload: createChunkedUploader({
url: '/api/upload/chunk',
}),
});

return (
<div>
<div {...getDropProps()}>
<input {...getInputProps()} />
<p>Thả tệp vào đây</p>
</div>

{files.map(file => (
<div key={file.id}>
<span>{file.name}</span>
<span>{file.progress}%</span>
<span>{file.status}</span>

{file.status === 'uploading' && (
<button onClick={() => actions.cancel(file.id)}>
Tạm dừng
</button>
)}

{file.status === 'paused' && (
<button onClick={() => actions.retry([file.id])}>
Tiếp tục
</button>
)}
</div>
))}

<button onClick={() => actions.upload()}>
Bắt đầu tất cả
</button>
</div>
);
}

Theo dõi tiến trình với khối

import { useState } from 'react';

function DetailedChunkProgress() {
const [chunkProgress, setChunkProgress] = useState<Map<string, number[]>>(
new Map()
);

const { files, actions, getDropProps, getInputProps } = useDropup({
upload: createChunkedUploader({
url: '/api/upload/chunk',
chunkSize: 1024 * 1024, // Khối 1MB để dễ quan sát

onChunkProgress: (file, chunkIndex, progress) => {
setChunkProgress(prev => {
const next = new Map(prev);
const fileProgress = next.get(file.id) || [];
fileProgress[chunkIndex] = progress;
next.set(file.id, fileProgress);
return next;
});
},
}),
});

return (
<div>
<div {...getDropProps()} style={styles.dropzone}>
<input {...getInputProps()} />
<p>Thả tệp vào đây</p>
</div>

{files.map(file => {
const chunks = chunkProgress.get(file.id) || [];
const totalChunks = Math.ceil(file.size / (1024 * 1024));

return (
<div key={file.id} style={styles.fileCard}>
<p>{file.name}</p>

{/* Trực quan hóa tiến trình khối */}
<div style={styles.chunkGrid}>
{Array.from({ length: totalChunks }).map((_, i) => (
<div
key={i}
style={{
...styles.chunkBlock,
backgroundColor: chunks[i] === 100
? '#4caf50'
: chunks[i] > 0
? '#8bc34a'
: '#eee',
}}
title={`Khối ${i + 1}: ${chunks[i] || 0}%`}
/>
))}
</div>

<p>Tổng thể: {file.progress}%</p>
</div>
);
})}

<button onClick={() => actions.upload()}>
Tải lên
</button>
</div>
);
}

const styles = {
dropzone: {
border: '2px dashed #ccc',
padding: 40,
textAlign: 'center' as const,
marginBottom: 20,
},
fileCard: {
padding: 16,
border: '1px solid #eee',
borderRadius: 8,
marginBottom: 12,
},
chunkGrid: {
display: 'flex',
flexWrap: 'wrap' as const,
gap: 4,
margin: '12px 0',
},
chunkBlock: {
width: 20,
height: 20,
borderRadius: 4,
transition: 'background-color 0.2s',
},
};

Khuyến nghị kích thước khối

Kích thước tệpKích thước khối khuyến nghị
< 10 MBKhông cần chia khối
10-100 MB5 MB
100 MB - 1 GB10 MB
> 1 GB20-50 MB
Hiệu suất

Khối lớn hơn = ít yêu cầu hơn, nhưng phục hồi lâu hơn khi thất bại. Khối nhỏ hơn = nhiều overhead hơn, nhưng khả năng tiếp tục tốt hơn.