django models.FileField 保存文件的几种方式

作者在 2022-11-07 18:15:19 发布以下内容
假设是一个model,名为Attach
class Attach(models.Model):
    file = FileField(upload_to="files/%Y/%m/%d")

保存上传文件,这个最简单:
def upload(request):
    attach = Attach()
    attach.file = request.FILES.get('file')
    attach.save()

保存网络上采集的文件:
import requests
from django.core.files.base import ContentFile

def upload(request):
    img_binary = requests.get(http_img_src, verify=False).content
    attach = Attach()
    attach.file.save('image.png', ContentFile(img_binary))
    attach.save()

附加上本地的文件:
from django.core.files import File

def upload(request):
    attach = Attach()
    attach.file.save('image.png', File(open('/home/root/image.png', 'rb')))
    attach.save()

Python | 阅读 140 次
文章评论,共0条
游客请输入验证码
浏览2559698次
文章归档