files.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. import hashlib
  2. import os
  3. import uuid
  4. from datetime import datetime
  5. from django.contrib.auth.decorators import login_required
  6. from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
  7. from django.http import HttpResponseRedirect, JsonResponse
  8. from django.shortcuts import render
  9. from django.views.decorators.clickjacking import xframe_options_sameorigin
  10. from blog import models
  11. from system import settings
  12. from system.error.ServerException import ServerException
  13. @xframe_options_sameorigin
  14. @login_required(login_url='/')
  15. def upload_markdown_img(request):
  16. file_obj = request.FILES.get('file')
  17. try:
  18. file_record = save_file(file_obj=file_obj)
  19. except Exception as e:
  20. return JsonResponse({"errno": 1, "message": str(e)})
  21. from PIL import Image
  22. img = Image.open(file_record.file_path + file_record.file_name)
  23. width, height = img.size
  24. print('Image size: {}x{}'.format(width, height))
  25. return JsonResponse({"errno": 0, "data": {
  26. 'url': file_record.file_net_path,
  27. 'alt': f'{width},{height}',
  28. "href": file_record.file_net_path,
  29. "width": width,
  30. "height": height
  31. }})
  32. def save_file(file_obj):
  33. def get_unique_str():
  34. uuid_str = str(uuid.uuid4())
  35. md5 = hashlib.md5()
  36. md5.update(uuid_str.encode('utf-8'))
  37. return md5.hexdigest()
  38. if file_obj is None:
  39. raise ServerException('文件不存在')
  40. else:
  41. file_type = file_obj.name.split('.')[-1]
  42. filename = get_unique_str() + '.' + file_obj.name.split('.')[-1]
  43. filepath = os.path.join(settings.UPLOAD_ROOT + '/' + file_type + '/')
  44. if not os.path.exists(filepath):
  45. os.mkdir(filepath)
  46. file_net_path = settings.DOMAIN + settings.UPLOAD_URL + '/' + file_type + '/' + filename
  47. f = open(filepath + filename, 'wb')
  48. for i in file_obj.chunks():
  49. f.write(i)
  50. f.close()
  51. file_record = models.FileRecord.objects.create(origin_name=file_obj.name, file_name=filename, file_path=filepath,
  52. create_date=datetime.now(),
  53. suffix=file_obj.name.split('.')[-1], file_net_path=file_net_path)
  54. return file_record
  55. @login_required(login_url='/')
  56. def files(request):
  57. # page: int = -1, is_paginator: bool = False, search_name: str = None
  58. if request.method == 'GET':
  59. page = request.GET.get('page')
  60. if page is None:
  61. page = 1
  62. else:
  63. page = int(page)
  64. search_name = request.GET.get('search_name')
  65. if search_name is None:
  66. files = models.FileRecord.objects.all()
  67. else:
  68. files = models.FileRecord.objects.filter(origin_name__contains=search_name)
  69. if page <= 0:
  70. page = 1
  71. paginator = Paginator(files, 15)
  72. try:
  73. files = paginator.page(page)
  74. except PageNotAnInteger:
  75. files = paginator.page(1)
  76. except EmptyPage:
  77. files = paginator.page(paginator.num_pages)
  78. return render(request, 'management/files/files.html', context={'files': files})
  79. @login_required(login_url='/')
  80. def delete(request):
  81. # page: int = -1, is_paginator: bool = False, search_name: str = None
  82. if request.method == 'GET':
  83. ids_str = request.GET.get("id")
  84. # models.files.objects.raw('DELETE FROM blog_files WHERE id IN (%s)', ids_str)
  85. models.FileRecord.objects.get(id=int(ids_str)).delete()
  86. return HttpResponseRedirect('/management/files') # 跳转到主界面
  87. else:
  88. raise ServerException("错误的请求")