作者在 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()