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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
#!/usr/bin/env python
# -*- coding: utf_8 -*-
import os
import sys
import copy
import time
import types
import json
import logging
import traceback
import re
import tempfile
import shutil
import base64
import uuid
from hashlib import md5 as fmd5
from urllib import parse
from datetime import datetime
from threading import Thread
from werkzeug.security import check_password_hash
from app.setting import config
from utils import md5_salt, random_string
logger = logging.getLogger("UploadManager")
FileStoragePath = os.getcwd()
# 判断目录是否存在,不存在则创建
# if not os.path.exists(os.path.join(FileStoragePath, config.get("UPLOAD_DIR"))):
# os.makedirs(os.path.join(FileStoragePath, config.get("UPLOAD_DIR")))
def ajaxCheckAccess(path):
realpath = os.path.realpath(path)
if not realpath.startswith(FileStoragePath):
return False
return True
def checkPath(path):
if not path:
return False, {"code": -1, "data": None, "message": "[%s] arg missed!" % path}
fpath = os.path.abspath(os.sep.join(
[os.path.abspath(FileStoragePath), path]))
if not ajaxCheckAccess(fpath):
return False, {"code": -1, "data": None, "message": "You have no access to [%s]!" % fpath}
if not os.path.exists(fpath):
return False, {"code": -1, "data": None, "message": "[%s] is not existed!" % fpath}
return True, os.path.abspath(fpath)
def saveToFile(saveFile, content):
try:
tfn = tempfile.mktemp()
tf = open(tfn, 'w+b')
tf.write(content)
tf.close()
os.rename(tfn, saveFile)
return True
except Exception as e:
traceback.print_exc()
logger.error(str(e))
return False
def getFileInfo(infofile):
info = dict()
info.update({
"isfile": os.path.isfile(infofile),
"isdir": os.path.isdir(infofile),
"size": os.path.getsize(infofile),
"atime": os.path.getatime(infofile),
"mtime": os.path.getmtime(infofile),
"ctime": os.path.getctime(infofile),
"name": os.path.basename(infofile)
})
return info
class UploadManager(object):
def __init__(self):
super(UploadManager, self).__init__()
def download(self, data):
obj = json.loads(data)
isAccessed, path = checkPath(obj["path"])
if not isAccessed:
return {"code": -1, "data": None, "message": "invaild access"}
if not os.path.isfile(path):
return {"code": -1, "data": None, "message": "Path [%s] is not a valid file!" % path}
try:
with open(path, "rb") as f:
content = base64.b64encode(f.read())
md5code = fmd5(content).hexdigest()
return {
"data": {
"content": content,
"md5": md5code,
"filename": os.path.basename(path)
},
"code": 0,
"message": "download file [%s] successfully!" % obj['path']
}
except Exception as e:
traceback.print_exc()
logger.error(str(e))
return {
"data": None,
"code": -1,
"message": "upload file [%s] failed!\n %s" % (obj['path'], repr(e))
}
def delete(self, data):
try:
isAccessed, path = checkPath(data["path"])
if not isAccessed:
return {"code": -1, "data": None, "message": "invaild access"}
if os.path.isfile(path):
os.remove(path)
return {"code": 0, "data": None, "message": "delete file [%s] successfully!" % path}
elif os.path.isdir(path):
os.rmdir(path)
return {"code": 0, "data": None, "message": "delete dir [%s] successfully!" % path}
else:
return {"code": 0, "data": None, "message": "Path [%s] is not a valid file or path!" % path}
except Exception as e:
traceback.print_exc()
logger.error(str(e))
return {"code": -1, "data": None, "message": repr(e)}
def dirlist(self, data):
obj = json.loads(data)
isAccessed, path = checkPath(obj["path"])
if not isAccessed:
return {"code": -1, "data": None, "message": "invaild access"}
result = []
for p in os.listdir(path):
result.append(getFileInfo(os.path.join(FileStoragePath, p)))
return {"code": 0, "result": result, "message": "Get [%s] successfully!" % path}
def filemd5(self, data):
obj = json.loads(data)
isAccessed, path = checkPath(obj["path"])
if not isAccessed:
return {"code": -1, "data": None, "message": "invaild access"}
if not os.path.isfile(path):
return {"code": -1, "data": None, "message": "Path [%s] is not a valid file!" % path}
with open(path, "rb") as f:
filemd5 = fmd5(f.read()).hexdigest()
return {"code": 0, "result": filemd5, "message": "Get md5 of [%s] successfully!" % path}
def fileinfo(self, data):
obj = json.loads(data)
isAccessed, path = checkPath(obj["path"])
if not isAccessed:
return {"code": -1, "data": None, "message": "invaild access"}
if not os.path.isfile(path):
return {"code": -1, "data": None, "message": "Path [%s] is not a valid file!" % path}
return {"code": 0, "result": getFileInfo(path), "message": "Get md5 of [%s] successfully!" % path}
uploadManager = UploadManager()