



项目为MyDjango,用到了一个项目应用index。
index的urls.py
from django.urls import path
from . import views
urlpatterns = [
# 定义路由
path('', views.upload, name='uploaded'),
]
index的views.py
from django.shortcuts import render
from django.http import HttpResponse
import os
def upload(request):
# 请求方法为POST时,执行文件上存
if request.method == "POST":
# 获取上传的文件,如果没有文件,则默认为None
myFile = request.FILES.get("myfile", None)
if not myFile:
return HttpResponse("no files for upload!")
# 打开特定的文件进行二进制的写操作
print("myFile.name", myFile.name)
f = open(os.path.join("", myFile.name), 'wb+')
# 分块写入文件
for chunk in myFile.chunks():
f.write(chunk)
f.close()
return HttpResponse("upload over!")
else:
# 请求方法为GET时,生成文件上存页面
return render(request, 'upload.html')
templates的upload.html
DOCTYPE html>
<html>
<body>
<form enctype="multipart/form-data" action="" method="post">
{% csrf_token %}
<input type="file" name="myfile" />
<br>
<input type="submit" value="上存文件"/>
form>
body>
html>
文件对象myFile提供了以下属性来获取文件信息。