编写html页面:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>上传图片</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
        <p align="center"><input type="file" name="filename" /></p>
        <p align="center"><input type="submit" value="上传" /></p>
</form>
</body>
</html>

效果如图(太丑了):

编写view视图函数:

def upload(request):
    if request.method == "GET":
        return render(request,"upload.html")
    if request.method == "POST":
        # TODO 获取上传文件的处理对象,通过对象获取里面文件名称和内容
        img = request.FILES.get("filename", None)
        print(img)
        # print(img.name)   # 获取文件名称
        # print(img.chunks)  # 获取文件内容
        # 创建文件
        save_path = '{}/up_image/{}'.format(settings.MEDIA_ROOT,img.name)
        with open(save_path,'wb') as f:
            for content in img.chunks():
                f.write(content)
        # 报存到数据库
        FileUpload.objects.create(name=img.name)
        return HttpResponse("ok")

添加modes模型生成数据库表:

class FileUpload(models.Model):
    '''上传文件或图片'''
    name = models.CharField(max_length=30,
                            blank=True,
                            null=True,
                            verbose_name="名称")
    image = models.ImageField(upload_to="up_image",
                              blank=True,
                              null=True,
                              verbose_name="上传图片"
                              )
    file = models.FileField(upload_to="up_file",
                            blank=True,
                            null=True,
                            verbose_name="上传文件"
                            )
    add_time = models.DateTimeField(auto_now_add=True,
                                    verbose_name="上传时间")

    def __str__(self):
        return self.__doc__

    class Meta():  # TODO 后台显示中文
        verbose_name = "上传文件和图片"
        verbose_name_plural = verbose_name

添加urls映射访问地址:

访问地址上传图片,抓包如图:

上传成功:

数据库存储的字段: