Python——文件上传
_1、原始方法:
表单设置enctype="multipart/form-data"
在视图中通过request.FILES来获取文件对象
将文件保存到磁盘
def uploaded_file(f):
""" 保存文件 """
with open('media/file/name.jpg', 'wb+') as dest:
for chunk in f.chunks():
dest.write(chunk)
weibo/urls.py
# 文件上传
path('file/upload/origin/', views.file_upload_origin, name='file_upload_origin')
weibo/views.py
def file_upload_origin(request):
""" 原始的文件上传 """
if request.method == 'POST':
# 获取上传的文件对象,二进制
file = request.FILES.get('avatar', None)
filename = os.path.join(settings.MEDIA_ROOT, 'test.jpg')
with open(filename, 'wb+') as f:
for chunk in file.chunks():
f.write(chunk)
print('上传成功')
return render(request, 'file_upload_origin.html')
weibo/templates/file_upload_origin.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>原始的文件上传</title>
</head>
<body>
<form action="." method="post" enctype="multipart/form-data">
<input type="file" name="avatar">
<input type="submit" value="开始上传">
</form>
</body>
</html>
_2、结合ORM模型方法:
weibo/urls.py
# ORM模型文件上传
path('file/upload/form/', views.file_upload_forms, name='file_upload_forms')
weibo/forms.py
class AvatarUploadForm(forms.Form):
""" 头像上传Form """
remark = forms.CharField(label='备注', max_length=32)
avatar = forms.ImageField(label='头像')
weibo/views.py
def file_upload_forms(request):
""" ORM模型文件上传 """
if request.method == 'POST':
form = AvatarUploadForm(request.POST, request.FILES)
if form.is_valid():
# 保存备注
# 保存图片
file = request.FILES.get('avatar', None)
filename = os.path.join(settings.MEDIA_ROOT, 'test.jpg')
with open(filename, 'wb+') as f:
for chunk in file.chunks():
f.write(chunk)
print('上传成功')
else:
form = AvatarUploadForm()
return render(request, 'file_upload_forms.html', {
'form': form
})
weibo/templates/file_upload_forms.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ORM模型文件上传</title>
</head>
<body>
<form action="." method="post" enctype="multipart/form-data">
{{ form.as_p }}
<input type="submit" value="上传">
</form>
</body>
</html>
_3、结合ORM模型上传
表单设置enctype="multipart/form-data"
在模型中使用models.ImageField
在表单中使用forms.ImageField
weibo/forms.py
class WeiboImageForm(forms.ModelForm):
""" 微博图片上传 """
content = forms.CharField(label='微博内容', max_length=256, widget=forms.Textarea(attrs={
'placeholder': '请输入微博内容',
}))
class Meta:
model = WeiboImage
fields = ['image']
# def clean_content(self):
# pass
def save(self, user, commit=False):
# 先不保存到数据库,先得到对象,接下来对这个对象进行修改,然后再保存
obj = super().save(commit)
data = self.cleaned_data
content = data['content']
# 1、创建微博的记录
weibo = Weibo.objects.create(user=user, content=content)
# 2、修改微博关联关系
obj.weibo = weibo
obj.save()
return obj
weibo/urls.py
path('file/upload/weibo/', views.file_upload_weibo, name='file_upload_weibo'),
weibo/views.py
def file_upload_weibo(request):
""" 发表带图片的微博 """
# 因为没有登录,默认用户来进行微博的发布
user = WeiboUser.objects.get(pk=1)
if request.method == 'POST':
form = WeiboImageForm(request.POST, request.FILES)
if form.is_valid():
obj = form.save(user,False)
print('保存成功', obj.pk)
else:
form = WeiboImageForm()
return render(request, 'file_upload_weibo.html', {
'form': form
})
weibo/templates/file_upload_weibo.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>结合ORM模型上传——发布带图片的微博</title>
</head>
<body>
<h3>微博发布</h3>
<form action="." method="post" enctype="multipart/form-data">
{{ form.as_p }}
<input type="submit" value="发布微博">
</form>
</body>
</html>
略懂,略懂....