首先配置settings.py文件,定义文件上传资料夹名称和路径
STATIC_URL = '/static/'
STATICFILES_DIRS=[
os.path.join(BASE_DIR,"static")
]
MEDIA_ROOT=[
os.path.join(BASE_DIR,"upload")
]
MEDIA_URL="/upload/"
前端HTML页面
<form action="/fileUpload.html" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p>username: <input type="text" name="username"></p>
<p><input type="file" name="file"></p>
<p><input type="submit" value="上传"></p>
</form>
Views内容,这里使用的Form组件验证,但是没写内容,注意文件上传路径及文件名称,可以自行更改
from django.shortcuts import render,HttpResponse
from django import forms
#增加图片上传Form验证
class fileForm(forms.Form):
username = forms.CharField(
min_length=2,
error_messages={"min_lenth":"名字长度不够"}
)
file = forms.FileField(
)
# Create your views here.
def fileUpload(request):
if request.method=="GET":
return render(request,"fileupload.html")
elif request.method=="POST":
obj = fileForm(request.POST,request.FILES)
if obj.is_valid():
username=obj.cleaned_data["username"]
file = obj.cleaned_data["file"]
newfile = open("upload/"+file.name,"wb")
for item in file.chunks():
newfile.write(item)
newfile.close()
print(file.name,file.size,"ok")
return HttpResponse("OK1111")
else:
print("NG")
return HttpResponse("NG1111")
else:
print("hahaha")