drf 媒体资源配置
settings
# MEDIA 存放路径
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
# MEDIA 路由前缀
MEDIA_URL = "/media/"
urls.py
urlpatterns = [
# 匹配media路由
re_path(r"^media/(?P<path>.*)$", serve, {'document_root': settings.MEDIA_ROOT}, name='media')
]
访问
http://127.0.0.1:8000/media/qrcode.png
上传方法
import datetime
import os
from django.conf import settings
from django.core.files.storage import default_storage
# 命名去重与上传
def get_upload(file):
now_data = datetime.datetime.now().strftime('%Y/%m/%d')
upload_file = os.path.join(settings.MEDIA_ROOT, now_data)
file_path = os.path.join(upload_file, file.name)
upload_path = default_storage.save(file_path, file)
return default_storage.url(upload_path)
上传接口
@action(methods=['post'], detail=False, url_name=None)
def upload(self, request):
try:
file_path = get_upload(request.FILES.get('file'))
except Exception as e:
return Response(
{"msg": "上传失败", "code": returnCode.ERROR, "detail": e},
status=status.HTTP_200_OK)
# 拼接当前host路由路径
abs_url = request.build_absolute_uri(file_path)
return Response(
{"msg": "上传成功", "code": returnCode.SUCCESS, "data": {"abs_url": abs_url, "path": file_path}},
status=status.HTTP_200_OK)
本文作者:Sherwin
本文链接:https://www.cnblogs.com/sherwin1995/p/16979057.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步