创建一个应用
python3 manage.py startapp sandbox
创建文件夹
在sandbox
目录下创建一个templates
目录, 为了规范再在templates
目录创建一个和应用同名的目录sandbox
, 然后在创建一个upload.html
文件;
upload.html
文件主要内容如下:
<form id="filesub" action="/upload" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" id="file-uploader" name="userfile">
</form>
<script>
document.getElementById("file-uploader").onchange = function () {
document.getElementById("filesub").submit();
};
</script>
当打开文件后可以直接自动上传;
sandbox/views.py 处理函数
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
from pathlib import Path
import os
BASE_DIR = Path(__file__).resolve().parent.parent
MEDIA_ROOT = os.path.join(BASE_DIR, 'static\\upfile')
def upload(request):
if request.method == "GET":
return render(request, 'sandbox/upload.html')
if request.method == 'POST':
# 获取对象
obj = request.FILES.get('userfile')
# 上传文件的文件名
print(obj.name)
f = open(os.path.join(BASE_DIR, 'sandbox', 'static', 'upfile', obj.name), 'wb')
for chunk in obj.chunks():
f.write(chunk)
f.close()
return HttpResponse("OK")
配置路由
在项目下/项目文件/url.py中:
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('sandbox.urls')),
]