-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
75 lines (56 loc) · 2.43 KB
/
server.py
File metadata and controls
75 lines (56 loc) · 2.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#!/usr/bin/env python3
# coding=utf-8
import os
from flask import Flask, request, Response, render_template as rt, jsonify
app = Flask(__name__)
@app.route('/', methods=['GET'])
def index():
return rt('./index.html')
@app.route('/file/upload', methods=['POST'])
def upload_part(): # 接收前端上传的一个分片
task = request.form.get('task_id') # 获取文件的唯一标识符
chunk = request.form.get('chunk', 0) # 获取该分片在所有分片中的序号
filename = '%s%s' % (task, chunk) # 构造该分片的唯一标识符
upload_file = request.files['file']
upload_file.save('./upload/%s' % filename) # 保存分片到本地
return jsonify({"result": "success"})
@app.route('/file/merge', methods=['GET'])
def upload_success(): # 按序读出分片内容,并写入新文件
target_filename = request.args.get('filename') # 获取上传文件的文件名
task = request.args.get('task_id') # 获取文件的唯一标识符
chunk = 0 # 分片序号
with open('./upload/%s' % target_filename, 'wb') as target_file: # 创建新文件
while True:
try:
filename = './upload/%s%d' % (task, chunk)
source_file = open(filename, 'rb') # 按序打开每个分片
target_file.write(source_file.read()) # 读取分片内容写入新文件
source_file.close()
# except IOError, msg:
except Exception as ex:
print(ex)
break
chunk += 1
os.remove(filename) # 删除该分片,节约空间
# return rt('./index.html')
return jsonify({"result": "success"})
@app.route('/file/list', methods=['GET'])
def file_list():
files_info = dict()
files = os.listdir('./upload/') # 获取文件目录
if files:
files_info['result'] = files
return jsonify(files_info)
@app.route('/file/download/<filename>', methods=['GET'])
def file_download(filename):
def send_chunk(): # 流式读取
store_path = './upload/%s' % filename
with open(store_path, 'rb') as target_file:
while True:
chunk = target_file.read(20 * 1024 * 1024)
if not chunk:
break
yield chunk
return Response(send_chunk(), content_type='application/octet-stream')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=6000, debug=False, threaded=True)