views.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. #coding:utf-8
  2. from importlib import import_module
  3. from django.http import HttpResponse
  4. import DjangoUeditor.settings as USettings
  5. import os
  6. import json
  7. from django.views.decorators.csrf import csrf_exempt
  8. from datetime import datetime
  9. import random
  10. import urllib
  11. def get_path_format_vars():
  12. return {
  13. "year":datetime.datetime.now().strftime("%Y"),
  14. "month":datetime.datetime.now().strftime("%m"),
  15. "day":datetime.datetime.now().strftime("%d"),
  16. "date": datetime.datetime.now().strftime("%Y%m%d"),
  17. "time":datetime.datetime.now().strftime("%H%M%S"),
  18. "datetime":datetime.datetime.now().strftime("%Y%m%d%H%M%S"),
  19. "rnd":random.randrange(100,999)
  20. }
  21. #保存上传的文件
  22. def save_upload_file(PostFile,FilePath):
  23. try:
  24. f = open(FilePath, 'wb')
  25. for chunk in PostFile.chunks():
  26. f.write(chunk)
  27. except Exception as E:
  28. f.close()
  29. return u"写入文件错误:"+ E.message
  30. f.close()
  31. return u"SUCCESS"
  32. @csrf_exempt
  33. def get_ueditor_settings(request):
  34. return HttpResponse(json.dumps(USettings.UEditorUploadSettings,ensure_ascii=False), content_type="application/javascript")
  35. @csrf_exempt
  36. def get_ueditor_controller(request):
  37. """获取ueditor的后端URL地址 """
  38. action=request.GET.get("action","")
  39. reponseAction={
  40. "config":get_ueditor_settings,
  41. "uploadimage":UploadFile,
  42. "uploadscrawl":UploadFile,
  43. "uploadvideo":UploadFile,
  44. "uploadfile":UploadFile,
  45. "catchimage":catcher_remote_image,
  46. "listimage":list_files,
  47. "listfile":list_files
  48. }
  49. return reponseAction[action](request)
  50. @csrf_exempt
  51. def list_files(request):
  52. """列出文件"""
  53. if request.method!="GET":
  54. return HttpResponse(json.dumps(u"{'state:'ERROR'}") ,content_type="application/javascript")
  55. #取得动作
  56. action=request.GET.get("action","listimage")
  57. allowFiles={
  58. "listfile":USettings.UEditorUploadSettings.get("fileManagerAllowFiles",[]),
  59. "listimage":USettings.UEditorUploadSettings.get("imageManagerAllowFiles",[])
  60. }
  61. listSize={
  62. "listfile":USettings.UEditorUploadSettings.get("fileManagerListSize",""),
  63. "listimage":USettings.UEditorUploadSettings.get("imageManagerListSize","")
  64. }
  65. listpath={
  66. "listfile":USettings.UEditorUploadSettings.get("fileManagerListPath",""),
  67. "listimage":USettings.UEditorUploadSettings.get("imageManagerListPath","")
  68. }
  69. #取得参数
  70. list_size=long(request.GET.get("size",listSize[action]))
  71. list_start=long(request.GET.get("start",0))
  72. files=[]
  73. root_path=os.path.join(USettings.gSettings.MEDIA_ROOT,listpath[action]).replace("\\","/")
  74. files=get_files(root_path,root_path,allowFiles[action])
  75. if (len(files)==0):
  76. return_info={
  77. "state":u"未找到匹配文件!",
  78. "list":[],
  79. "start":list_start,
  80. "total":0
  81. }
  82. else:
  83. return_info={
  84. "state":"SUCCESS",
  85. "list":files[list_start:list_start+list_size],
  86. "start":list_start,
  87. "total":len(files)
  88. }
  89. return HttpResponse(json.dumps(return_info),content_type="application/javascript")
  90. def get_files(root_path,cur_path, allow_types=[]):
  91. files = []
  92. items = os.listdir(cur_path)
  93. for item in items:
  94. item=unicode(item)
  95. item_fullname = os.path.join(root_path,cur_path, item).replace("\\", "/")
  96. if os.path.isdir(item_fullname):
  97. files.extend(get_files(root_path,item_fullname, allow_types))
  98. else:
  99. ext = os.path.splitext(item_fullname)[1]
  100. is_allow_list= (len(allow_types)==0) or (ext in allow_types)
  101. if is_allow_list:
  102. files.append({
  103. "url":urllib.basejoin(USettings.gSettings.MEDIA_URL ,os.path.join(os.path.relpath(cur_path,root_path),item).replace("\\","/" )),
  104. "mtime":os.path.getmtime(item_fullname)
  105. })
  106. return files
  107. @csrf_exempt
  108. def UploadFile(request):
  109. """上传文件"""
  110. if not request.method=="POST":
  111. return HttpResponse(json.dumps(u"{'state:'ERROR'}"),content_type="application/javascript")
  112. state="SUCCESS"
  113. action=request.GET.get("action")
  114. #上传文件
  115. upload_field_name={
  116. "uploadfile":"fileFieldName","uploadimage":"imageFieldName",
  117. "uploadscrawl":"scrawlFieldName","catchimage":"catcherFieldName",
  118. "uploadvideo":"videoFieldName",
  119. }
  120. UploadFieldName=request.GET.get(upload_field_name[action],USettings.UEditorUploadSettings.get(action,"upfile"))
  121. #上传涂鸦,涂鸦是采用base64编码上传的,需要单独处理
  122. if action=="uploadscrawl":
  123. upload_file_name="scrawl.png"
  124. upload_file_size=0
  125. else:
  126. #取得上传的文件
  127. file=request.FILES.get(UploadFieldName,None)
  128. if file is None:return HttpResponse(json.dumps(u"{'state:'ERROR'}") ,content_type="application/javascript")
  129. upload_file_name=file.name
  130. upload_file_size=file.size
  131. #取得上传的文件的原始名称
  132. upload_original_name,upload_original_ext=os.path.splitext(upload_file_name)
  133. #文件类型检验
  134. upload_allow_type={
  135. "uploadfile":"fileAllowFiles",
  136. "uploadimage":"imageAllowFiles",
  137. "uploadvideo":"videoAllowFiles"
  138. }
  139. if upload_allow_type.has_key(action):
  140. allow_type= list(request.GET.get(upload_allow_type[action],USettings.UEditorUploadSettings.get(upload_allow_type[action],"")))
  141. if not upload_original_ext in allow_type:
  142. state=u"服务器不允许上传%s类型的文件。" % upload_original_ext
  143. #大小检验
  144. upload_max_size={
  145. "uploadfile":"filwMaxSize",
  146. "uploadimage":"imageMaxSize",
  147. "uploadscrawl":"scrawlMaxSize",
  148. "uploadvideo":"videoMaxSize"
  149. }
  150. max_size=long(request.GET.get(upload_max_size[action],USettings.UEditorUploadSettings.get(upload_max_size[action],0)))
  151. if max_size!=0:
  152. from utils import FileSize
  153. MF=FileSize(max_size)
  154. if upload_file_size>MF.size:
  155. state=u"上传文件大小不允许超过%s。" % MF.FriendValue
  156. #检测保存路径是否存在,如果不存在则需要创建
  157. upload_path_format={
  158. "uploadfile":"filePathFormat",
  159. "uploadimage":"imagePathFormat",
  160. "uploadscrawl":"scrawlPathFormat",
  161. "uploadvideo":"videoPathFormat"
  162. }
  163. path_format_var=get_path_format_vars()
  164. path_format_var.update({
  165. "basename":upload_original_name,
  166. "extname":upload_original_ext[1:],
  167. "filename":upload_file_name,
  168. })
  169. #取得输出文件的路径
  170. OutputPathFormat,OutputPath,OutputFile=get_output_path(request,upload_path_format[action],path_format_var)
  171. #所有检测完成后写入文件
  172. if state=="SUCCESS":
  173. if action=="uploadscrawl":
  174. state=save_scrawl_file(request, os.path.join(OutputPath,OutputFile))
  175. else:
  176. #保存到文件中,如果保存错误,需要返回ERROR
  177. upload_module_name = USettings.UEditorUploadSettings.get("upload_module", None)
  178. if upload_module_name:
  179. mod = import_module(upload_module_name)
  180. state = mod.upload(file, OutputPathFormat)
  181. else:
  182. state = save_upload_file(file, os.path.join(OutputPath, OutputFile))
  183. #返回数据
  184. return_info = {
  185. 'url': urllib.basejoin(USettings.gSettings.MEDIA_URL , OutputPathFormat) , # 保存后的文件名称
  186. 'original': upload_file_name, #原始文件名
  187. 'type': upload_original_ext,
  188. 'state': state, #上传状态,成功时返回SUCCESS,其他任何值将原样返回至图片上传框中
  189. 'size': upload_file_size
  190. }
  191. return HttpResponse(json.dumps(return_info,ensure_ascii=False),content_type="application/javascript")
  192. @csrf_exempt
  193. def catcher_remote_image(request):
  194. """远程抓图,当catchRemoteImageEnable:true时,
  195. 如果前端插入图片地址与当前web不在同一个域,则由本函数从远程下载图片到本地
  196. """
  197. if not request.method=="POST":
  198. return HttpResponse(json.dumps( u"{'state:'ERROR'}"),content_type="application/javascript")
  199. state="SUCCESS"
  200. allow_type= list(request.GET.get("catcherAllowFiles",USettings.UEditorUploadSettings.get("catcherAllowFiles","")))
  201. max_size=long(request.GET.get("catcherMaxSize",USettings.UEditorUploadSettings.get("catcherMaxSize",0)))
  202. remote_urls=request.POST.getlist("source[]",[])
  203. catcher_infos=[]
  204. path_format_var=get_path_format_vars()
  205. for remote_url in remote_urls:
  206. #取得上传的文件的原始名称
  207. remote_file_name=os.path.basename(remote_url)
  208. remote_original_name,remote_original_ext=os.path.splitext(remote_file_name)
  209. #文件类型检验
  210. if remote_original_ext in allow_type:
  211. path_format_var.update({
  212. "basename":remote_original_name,
  213. "extname":remote_original_ext[1:],
  214. "filename":remote_original_name
  215. })
  216. #计算保存的文件名
  217. o_path_format,o_path,o_file=get_output_path(request,"catcherPathFormat",path_format_var)
  218. o_filename=os.path.join(o_path,o_file).replace("\\","/")
  219. #读取远程图片文件
  220. try:
  221. remote_image=urllib.urlopen(remote_url)
  222. #将抓取到的文件写入文件
  223. try:
  224. f = open(o_filename, 'wb')
  225. f.write(remote_image.read())
  226. f.close()
  227. state="SUCCESS"
  228. except Exception as E:
  229. state=u"写入抓取图片文件错误:%s" % E.message
  230. except Exception as E:
  231. state=u"抓取图片错误:%s" % E.message
  232. catcher_infos.append({
  233. "state":state,
  234. "url":urllib.basejoin(USettings.gSettings.MEDIA_URL , o_path_format),
  235. "size":os.path.getsize(o_filename),
  236. "title":os.path.basename(o_file),
  237. "original":remote_file_name,
  238. "source":remote_url
  239. })
  240. return_info={
  241. "state":"SUCCESS" if len(catcher_infos) >0 else "ERROR",
  242. "list":catcher_infos
  243. }
  244. return HttpResponse(json.dumps(return_info,ensure_ascii=False),content_type="application/javascript")
  245. def get_output_path(request,path_format,path_format_var):
  246. #取得输出文件的路径
  247. OutputPathFormat=(request.GET.get(path_format,USettings.UEditorSettings["defaultPathFormat"]) % path_format_var).replace("\\","/")
  248. #分解OutputPathFormat
  249. OutputPath,OutputFile=os.path.split(OutputPathFormat)
  250. OutputPath=os.path.join(USettings.gSettings.MEDIA_ROOT,OutputPath)
  251. if not OutputFile:#如果OutputFile为空说明传入的OutputPathFormat没有包含文件名,因此需要用默认的文件名
  252. OutputFile=USettings.UEditorSettings["defaultPathFormat"] % path_format_var
  253. OutputPathFormat=os.path.join(OutputPathFormat,OutputFile)
  254. if not os.path.exists(OutputPath):
  255. os.makedirs(OutputPath)
  256. return ( OutputPathFormat,OutputPath,OutputFile)
  257. #涂鸦功能上传处理
  258. @csrf_exempt
  259. def save_scrawl_file(request,filename):
  260. import base64
  261. try:
  262. content=request.POST.get(USettings.UEditorUploadSettings.get("scrawlFieldName","upfile"))
  263. f = open(filename, 'wb')
  264. f.write(base64.decodestring(content))
  265. f.close()
  266. state="SUCCESS"
  267. except Exception as E:
  268. state="写入图片文件错误:%s" % E.message
  269. return state