views.py 11 KB

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