简体   繁体   English

将 base64 转换为 .jpg 文件,然后保存在 Django 数据库中

[英]Converting base64 to .jpg file, then saving in Django database

def upload_image(request):
    if request.is_ajax and request.POST:
        image = request.POST.get('image')

        image_name = request.POST.get('image_name')

        imgdata = base64.b64decode(image + '==')

        extension = image_name.split('.')[1].lower()

        image_name = '{}_{}_profile_image.{}'.format(request.user.first_name, request.user.last_name, extension)

        with open(image_name, "wb") as image_file:
            image_file.write(imgdata)

        upload = ProfileImage(
            file=image_file,
            user = request.user.username
            )
        upload.save()
    data = {

    }
    return JsonResponse(data)

I am trying to crop images in Django using Croppie.js.我正在尝试使用 Croppie.js 在 Django 中裁剪图像。 The images are then uploaded to an S3 bucket.然后将图像上传到 S3 存储桶。

I have the cropping working and it is returning the image cropped as a base64 string.我有裁剪工作,它返回裁剪为 base64 字符串的图像。 I decoded it and write it to a new image file so that it could be then saved in the database.我解码它并将其写入一个新的图像文件,以便可以将其保存在数据库中。

When it it gets to upload.save() I am getting the error.当它到达 upload.save() 时,我收到错误消息。

AttributeError: '_io.BufferedWriter' object has no attribute '_committed'

I'm not sure what the problem is.我不确定问题是什么。 This is my first time working with base64 images and im not sure if im missing something when i'm converting back to a file or what is going on.这是我第一次使用 base64 图像,我不确定在转换回文件时是否遗漏了什么或发生了什么。

I was able to find a solution by using ContentFile我能够通过使用ContentFile找到解决方案

from django.core.files.base import ContentFile

def upload_image(request):
        if request.is_ajax and request.POST:
        image = request.POST.get('image')

        image_name = request.POST.get('image_name')

        extension = image_name.split('.')[1].lower()

        image_name = '{}_{}_profile_image.{}'.format(request.user.first_name, request.user.last_name, extension)

        imgStr = image.split(';base64')

        data = ContentFile(base64.b64decode(imgStr[1]), name=image_name)

        upload = Upload(
            file=data,
            user = request.user.username
            )
        # Saves upload to S3 bucket
        upload.save()
    data = {

    }
    return JsonResponse(data)

It converts the base64 string to a file that is readable by django.它将 base64 字符串转换为 django 可读的文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM