diff --git a/account/serializers.py b/account/serializers.py index 21ae24aa..31ebd097 100644 --- a/account/serializers.py +++ b/account/serializers.py @@ -131,6 +131,10 @@ class ImageUploadForm(forms.Form): image = forms.FileField() +class FileUploadForm(forms.Form): + file = forms.FileField() + + class RankInfoSerializer(serializers.ModelSerializer): user = UsernameSerializer() diff --git a/utils/urls.py b/utils/urls.py index ca9fb0f1..7e0128e5 100644 --- a/utils/urls.py +++ b/utils/urls.py @@ -1,7 +1,8 @@ from django.conf.urls import url -from .views import SimditorImageUploadAPIView +from .views import SimditorImageUploadAPIView, SimditorFileUploadAPIView urlpatterns = [ - url(r"^upload_image/?$", SimditorImageUploadAPIView.as_view(), name="upload_image") + url(r"^upload_image/?$", SimditorImageUploadAPIView.as_view(), name="upload_image"), + url(r"^upload_file/?$", SimditorFileUploadAPIView.as_view(), name="upload_file") ] diff --git a/utils/views.py b/utils/views.py index c3e3861d..faced3ab 100644 --- a/utils/views.py +++ b/utils/views.py @@ -1,6 +1,6 @@ import os from django.conf import settings -from account.serializers import ImageUploadForm +from account.serializers import ImageUploadForm, FileUploadForm from utils.shortcuts import rand_str from utils.api import CSRFExemptAPIView import logging @@ -35,10 +35,41 @@ class SimditorImageUploadAPIView(CSRFExemptAPIView): except IOError as e: logger.error(e) return self.response({ - "success": True, + "success": False, "msg": "Upload Error", - "file_path": f"{settings.UPLOAD_PREFIX}/{img_name}"}) + "file_path": ""}) return self.response({ "success": True, "msg": "Success", "file_path": f"{settings.UPLOAD_PREFIX}/{img_name}"}) + + +class SimditorFileUploadAPIView(CSRFExemptAPIView): + request_parsers = () + + def post(self, request): + form = FileUploadForm(request.POST, request.FILES) + if form.is_valid(): + file = form.cleaned_data["file"] + else: + return self.response({ + "success": False, + "msg": "Upload failed" + }) + + suffix = os.path.splitext(file.name)[-1].lower() + file_name = rand_str(10) + suffix + try: + with open(os.path.join(settings.UPLOAD_DIR, file_name), "wb") as f: + for chunk in file: + f.write(chunk) + except IOError as e: + logger.error(e) + return self.response({ + "success": False, + "msg": "Upload Error"}) + return self.response({ + "success": True, + "msg": "Success", + "file_path": f"{settings.UPLOAD_PREFIX}/{file_name}", + "file_name": file.name}) \ No newline at end of file diff --git a/utils/xss_filter.py b/utils/xss_filter.py index 1b45d89c..fe4f7aa8 100644 --- a/utils/xss_filter.py +++ b/utils/xss_filter.py @@ -142,7 +142,7 @@ class XSSHtml(HTMLParser): return attrs def _true_url(self, url): - prog = re.compile(r"^(http|https|ftp)://.+", re.I | re.S) + prog = re.compile(r"(^(http|https|ftp)://.+)|(^/)", re.I | re.S) if prog.match(url): return url else: