前端vue大文件切片上传
时间: 2024-01-01 14:04:51 浏览: 120
前端可以使用 `slice` 方法将大文件切片,然后使用 `XMLHttpRequest` 对象发送每个切片,最后在后端将所有切片合并成一个完整的文件。
以下是一个基本的示例代码:
```html
<template>
<div>
<input type="file" @change="handleFileUpload">
<button @click="uploadFile">上传</button>
</div>
</template>
<script>
export default {
data() {
return {
file: null,
chunkSize: 1024 * 1024, // 每个切片大小为1MB
chunks: [], // 切片数组
};
},
methods: {
handleFileUpload(event) {
this.file = event.target.files[0];
this.chunks = this.createChunks();
},
createChunks() {
const fileSize = this.file.size;
const chunks = [];
let start = 0;
let end = this.chunkSize;
while (start < fileSize) {
chunks.push(this.file.slice(start, end));
start = end;
end = start + this.chunkSize;
}
return chunks;
},
async uploadFile() {
const url = 'your-upload-url';
const totalChunks = this.chunks.length;
for (let i = 0; i < totalChunks; i++) {
const formData = new FormData();
formData.append('chunk', this.chunks[i]);
formData.append('filename', this.file.name);
formData.append('totalChunks', totalChunks);
formData.append('chunkNumber', i + 1);
const xhr = new XMLHttpRequest();
xhr.open('POST', url);
xhr.send(formData);
}
},
},
};
</script>
```
在后端,需要接收每个切片并将其追加到一个临时文件中,直到所有切片都上传完成。然后将所有切片合并成一个完整的文件。以下是一个基本的示例代码:
```python
import os
from flask import Flask, request
app = Flask(__name__)
@app.route('/upload', methods=['POST'])
def upload():
chunk = request.files['chunk']
filename = request.form['filename']
total_chunks = int(request.form['totalChunks'])
chunk_number = int(request.form['chunkNumber'])
# 为切片创建一个临时文件
temp_dir = 'temp/'
if not os.path.exists(temp_dir):
os.makedirs(temp_dir)
temp_file_path = os.path.join(temp_dir, f'{filename}.part{chunk_number}')
chunk.save(temp_file_path)
# 当所有切片都上传时,将它们合并成一个文件
if chunk_number == total_chunks:
with open(filename, 'wb') as f:
for i in range(1, total_chunks + 1):
temp_file_path = os.path.join(temp_dir, f'{filename}.part{i}')
with open(temp_file_path, 'rb') as temp_file:
f.write(temp_file.read())
os.remove(temp_file_path)
return 'OK'
if __name__ == '__main__':
app.run()
```
阅读全文
相关推荐


















