我通过表单收到一张图片,不想像通常保存在FileField
中,而是以Base64的形式保存在CharField
中。这是我的当前设置:
models.py
class Image(models.Model):
company = models.ForeignKey(Company)
img = models.TextField()
img_id = models.CharField(blank=True, null=True, max_length=64)
img_class = models.CharField(blank=True, null=True, max_length=64)
created = models.DateField(auto_now_add=True, editable=False)
forms.py
class ImageForm(forms.Form):
img = forms.ImageField()
img_id = forms.CharField(required=False)
img_class = forms.CharField(required=False)
views.py
class ImageUploadView(LoginRequiredMixin, FormView):
form_class = ImageForm
template_name = "upload.html"
success_url = reverse_lazy("home")
def form_valid(self, form):
account = Account.objects.get(user=self.request.user)
html = Html.objects.get(company=account.company)
if self.request.user.is_authenticated():
company = Company.objects.get(account=account)
form_img = form.cleaned_data['img']
print(form_img.__dict__.keys())
print(form_img.image)
return super(ImageUploadView, self).form_valid(form)
print(form_img.__dict__.keys())
的输出结果是:['file', 'content_type_extra', 'image', 'charset', '_name', 'content_type', '_size', 'field_name']
对于一个PNG图片,print(form_img.image)
的输出为:
<PIL.PngImagePlugin.PngImageFile image mode=RGBA size=183x161 at 0x7F087B2E6B90>
对于JPG格式的文件,它是这样的:
<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=400x400 at 0x7F087B16EC50>
从流中接收到的图像是否可以编码为base64并保存到数据库中,而不需要在其他地方临时保存它?
编辑:现在已经搞定了!
b64_img = base64.b64encode(form_img.file.read())
那基本上就是全部内容了!