Django:如何将字节对象保存到models.FileField? [英] Django: how save bytes object to models.FileField?

查看:91
本文介绍了Django:如何将字节对象保存到models.FileField?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Web应用程序具有以下结构:

My web application has the following structure:

  1. 使用Django的后端
  2. 使用React的前端.

我有一个与React的表格.我从客户端表单发送文件,并在我的Django应用程序中使用API​​View接收文件.

I have a form with React. I send a file from client form and I receive the file in my Django application with an APIView.

我收到一个m3u文件作为字节对象.

I receive a m3u file as bytes object.

b'------WebKitFormBoundaryIaAPDyj9Qrx8DrWA\r\nContent-Disposition: 
form-data; name="upload"; 
filename="test.m3u"\r\nContent-Type: audio/x- 
mpegurl\r\n\r\n#EXTM3U\n#EXTINF:-1 tvg-ID="" tvg-name="...

我会将Django模型中的文件保存到models.FileField并将bytes对象转换为m3u文件.你如何做到的?

I would save the file in a Django model to a models.FileField and convert bytes object to m3u file. How you do it?

推荐答案

  1. models.FileField(models.ImageField)需要像对象一样的django.core.files.base.File例如)

  1. models.FileField(models.ImageField) needs django.core.files.base.File like objects ex)

  • django.core.files.images.ImageFile

  • django.core.files.images.ImageFile

django.core.files.base.ContentFile

django.core.files.base.ContentFile

ImageFile或ContentFile需要两个参数.

ImageFile or ContentFile needs two args.

  1. IO对象:具有seek()方法(例如io.BytesIO).

  1. IO object : which has seek() method (ex) io.BytesIO).

name:str.(重要!没有名称,它将无法正常工作.)

name : str. (important! without name, it will not works).

  • bytes对象没有IO的方法(例如,seek()).应该将其转换为IO对象.

  • bytes object doesn't have IO's methods(ex) seek()). it should be converted to IO object.

    models.py

    models.py

        class Message(models.Model):
            image = models.ImageField(upload_to='message_image/%Y/%m', null=True)
    

    views.py或consumers.py

    views.py or consumers.py

        import io
        from django.core.files.images import ImageFile
        from myapp.models import Message
       
        def create_image_message(image_bytes):
            image = ImageFile(io.BytesIO(image_bytes), name='foo.jpg')  # << the answer!
            new_message = Message.objects.create(image=image)
    

    这篇关于Django:如何将字节对象保存到models.FileField?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆