views.py 11 KB

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