参考:

https://www.cnblogs.com/zerotest/p/14387266.html

https://blog.csdn.net/iteye_10850/article/details/82615387

在网站中对用户开放上传下载功能是很常见的需求。

最近领导提出,我们的api注册中心,需要支持用户使用python脚本对结果进行格式转换

于是我们添加了文件的上传下载功能

一、模型models

在模型中指定保存文件的字段

#底层mysql还是一个varchar类型,存的是文件在项目中的相对路径
result_filter = models.FileField(upload_to='{app_name}/', blank=True, null=True,max_length=100,verbose_name='结果转换脚本')

二、settings文件中指定文件目录

settings加入

MEDIA_URL = 'file/'
MEDIA_ROOT = 'file/'

 

MEDIA_ROOT = 'file/'

于是上传文件的路径就是MEDIA_ROOT = 'file/'与upload_to='appname/'连起来file/appname/

上传a.txt,目录为file/appname/a.txt。

MEDIA_URL = 'file/'

表示任何上传文件链接前缀为 'file/'与upload_to='appname/'连起来file/appname/

三、urls.py中配置上传下载的接口

这个是全局的urls.py

from django.conf import settings
from django.contrib import admin
from django.urls import path, include, re_path
from django.views.static import serve

urlpatterns = [
#...
    re_path(r"file/(?P<path>.*)$", serve, {"document_root": settings.MEDIA_ROOT}),
    
]

这样就大功告成了

相关文章:

  • 2021-11-08
  • 2021-12-26
  • 2021-10-24
  • 2021-07-10
  • 2022-02-15
  • 2021-10-06
  • 2021-06-19
  • 2022-01-25
猜你喜欢
  • 2022-12-23
  • 2021-11-23
  • 2021-12-08
  • 2022-12-23
  • 2022-01-26
  • 2022-01-05
相关资源
相似解决方案