views.py 11 KB

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