zoukankan      html  css  js  c++  java
  • django DefaultFileSystem Storage使用方法

    官方文档介绍:
    https://docs.djangoproject.com/en/3.1/ref/files/storage/

    源码解读:

    from django.core.files.storage import FileSystemStorage

     如果定义模型ImageField()

    img=models.ImageField()



     

    如果上传图片需要安装Pillow

    pip install Pillow

    设置

    1、首先在settings.py中定义MEDIA_ROOT与MEDIA_URL。例如:

    MEDIA_ROOT = os.path.join(BASE_DIR, "files")
    MEDIA_URL = "/files/"
    

    files可以是项目根目录的任何一个文件夹

    2、在urls.py的urlpatterns中,设置访问文件的url

    from django.views.generic import TemplateView
    url(r'^files/(?P<path>.*)$', serve, {"document_root": settings.MEDIA_ROOT})
    

    ?P<path>代表这一块的内容将作为参数path传给serve方法

    serve方法是django自带的处理静态文件的方法

    document_root是必须提供的文件位置

    注意如果文件放在url注册的document_root之外,前端是不能访问到这些文件的

    models.py

    file = models.FileField()

    1. 定义upload_to="background/"

      表示上传的文件将会存在$MEDIA_ROOT/background/下

    2. ImageField和FileField实际上是CharFields,所以可以设置blank=True

    serializers.py

    正常写一个ModelSerializer

    class FileSerializer(serializers.ModelSerializer):
        class Meta:
            model = File
            fields = "__all__"
    

    效果

    写完view中的逻辑和注册路由后,访问对应的接口可以看到FileField字段是一个上传文件的按钮

    上传文件后,该字段会返回可以访问文件的url

  • 相关阅读:
    wx小程序用canvas生成图片流程与注意事项
    mysql导入导出csv
    机房测速
    python 后台服务
    python获取硬件信息模块
    nagios外部命令接口
    nginx下的nagios pnp4nagios
    supervisor运行virtualenv环境下的nagios-api
    check_mk通用应用检测插件
    pnp4nagios 性能调优
  • 原文地址:https://www.cnblogs.com/SunshineKimi/p/13976433.html
Copyright © 2011-2022 走看看