前端通过 Dropzone 组件上传文件到后端,因此需要准备一个简易的后端来处理上传请求。

这里创建了一个名为 topic 的 app,在应用目录下创建 urls.py 文件:

from django.urls import path

from . import views

urlpatterns = [
    path('upload/', views.image_upload, name='jdd_upload'),
]

在项目 urls.py 中引用:

from django.conf.urls import include, url

urlpatterns = [
    url(r'^topic/', include('topic.urls')),
]

在应用 views.py 文件中定义上传功能:

from django.shortcuts import render
from django.http.response import HttpResponse
from django.core.files.storage import FileSystemStorage


def image_upload(request):
    if request.method == 'POST' and request.FILES['file']:
        thefile = request.FILES['file']
        fs = FileSystemStorage()
        filename = fs.save(thefile.name, thefile)
        file_url = fs.url(filename)
        return HttpResponse(file_url)
    else:
        return HttpResponse('error')

前端页面表单:

<form action="{% url 'jdd_upload' %}" class="dropzone">
    {% csrf_token %}
</form>

Reference