实现分片上传可以提高上传大文件时的可靠性和速度。以下是如何用 JavaScript 实现前端的分片上传,并用 FastAPI 实现后端处理分片的代码示例。
前端(JavaScript)
我们将使用 Blob.slice() 方法将文件分割成多个小块进行上传。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chunked File Upload</title>
</head>
<body>
<input type="file" id="fileInput">
<button onclick="uploadFile in Chunks()">Upload File in Chunks</button>
<script>
async function uploadFileInChunks() {
const fileInput = document.getElementById('fileInput');
const file = fileInput.files[0];
if (!file) {
alert('Please select a file');
return;
}
const chunkSize = 1024 * 1024; // 1MB
const totalChunks = Math.ceil(file.size / chunkSize);
const uploadURL = 'http://localhost:8000/upload';
for (let i = 0; i < totalChunks; i++) {
const start = i * chunkSize;
const end = Math.min(file.size, start + chunkSize);
const chunk = file.slice(start, end);
const formData = new FormData();
formData.append('chunk', chunk);
formData.append('chunkIndex', i);
formData.append('totalChunks', totalChunks);
formData.append('fileName', file.name);
try {
const response = await fetch(uploadURL, {
method: 'POST',
body: formData
});
if (!response.ok) {
alert(`Failed to upload chunk ${i}`);
return;
}
} catch (error) {
console.error("Error uploading chunk:", error);
alert("Upload failed, please try again.");
return;
}
}
alert("File uploaded successfully!");
}
</script>
</body>
</html>
后端(Python - FastAPI)
我们将实现一个简单的 FastAPI 应用来处理分片上传,并将它们保存到服务器上。
import os
from fastapi import FastAPI, UploadFile, Form
from fastapi.responses import JSONResponse
app = FastAPI()
UPLOAD_FOLDER = 'uploads'
if not os.path.exists(UPLOAD_FOLDER):
os.makedirs(UPLOAD_FOLDER)
@app.post("/upload")
async def upload_chunk(
chunk: UploadFile,
chunkIndex: int = Form(...),
totalChunks: int = Form(...),
fileName: str = Form(...)
):
try:
# 创建临时文件保存块
temp_file_path = os.path.join(UPLOAD_FOLDER, f"{fileName}.part{chunkIndex}")
with open(temp_file_path, 'wb') as f:
f.write(await chunk.read())
# 如果是最后一个块,合并所有分片
if chunkIndex == totalChunks - 1:
file_path = os.path.join(UPLOAD_FOLDER, fileName)
with open(file_path, 'wb') as output_file:
for i in range(totalChunks):
part_file_path = os.path.join(UPLOAD_FOLDER, f"{fileName}.part{i}")
with open(part_file_path, 'rb') as part_file:
output_file.write(part_file.read())
os.remove(part_file_path) # 删除临时分片文件
return JSONResponse(status_code=200, content={"message": "Chunk uploaded"})
except Exception as e:
return JSONResponse(status_code=500, content={"message": str(e)})
if __name__ == '__main__':
import uvicorn
uvicorn.run(app, host="127.0.0.1", port=8000)
说明
- Chunking: 在客户端,我们将文件分成小块(例如,1 MB 每块),并逐块上传到服务器。
- Multipart Handling: 使用
FormData 可以轻松包含带有块索引和总块数的元数据。
- Consolidation: 服务端检查是最后一个块后合并所有块,并清理临时文件。
- 错误处理: 包括了简单的错误处理,但在生产环境中可以更加完善,例如重试机制、更详细的错误日志等。
通过这种方式,您可以有效地处理大文件的上传,确保上传的可靠性和速度。