You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django3 FileSystemStorage上传文件未存入指定media子目录解决方法

问题原因
  • 你给FileSystemStorage传入的location是硬编码的相对路径,Django不会自动把这个相对路径和MEDIA_ROOT拼接,会直接以项目启动时的工作目录为根解析路径,很容易出现路径匹配偏差,最终文件落到默认的/media根目录。
  • 代码存在低级错误:处理第二个上传文件customFileInput2时,你用fs2实例完成了文件保存,但生成访问地址时错误调用了第一个存储实例fs的url()方法,就算存储路径正确,生成的文件访问链接也是错的。
  • 原代码没有判断文件字段是否存在于request.FILES中,用户漏传对应文件时会直接抛出KeyError。
修复步骤
  1. 先确认settings.py中已经正确配置媒体文件根参数:
# settings.py
import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# 媒体文件存储根目录
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
# 媒体文件访问前缀
MEDIA_URL = '/media/'
  1. 修改视图代码,用os.path.join拼接基于MEDIA_ROOT的绝对存储路径,修正url调用错误,补充文件存在判断:
from django.conf import settings
from django.core.files.storage import FileSystemStorage
from django.shortcuts import render, redirect, reverse
import os

def create_account_dentist(request):
    if request.method == 'POST':
        uploaded_file_url = ""
        uploaded_file_url2 = ""
        # 处理医师毕业证文件
        if 'customFileInput1' in request.FILES:
            myfile = request.FILES['customFileInput1']
            diploma_save_path = os.path.join(settings.MEDIA_ROOT, 'dentist/diplomas/')
            fs = FileSystemStorage(location=diploma_save_path)
            filename = fs.save(myfile.name, myfile)
            uploaded_file_url = fs.url(filename)
        # 处理政府官方证件文件
        if 'customFileInput2' in request.FILES:
            myfile2 = request.FILES['customFileInput2']
            gov_doc_save_path = os.path.join(settings.MEDIA_ROOT, 'dentist/government_docs/')
            fs2 = FileSystemStorage(location=gov_doc_save_path)
            filename2 = fs2.save(myfile2.name, myfile2)
            # 修正:调用对应存储实例fs2的url方法
            uploaded_file_url2 = fs2.url(filename2)
        return redirect(reverse('dentist-section'))
    return render(request, 'create-account-dentist.html')
额外说明
  • 不需要手动创建dentist/diplomas、dentist/government_docs目录,FileSystemStorage保存文件时会自动递归创建不存在的父目录。
  • 启动Django服务时确保执行runserver命令的路径是项目根目录(即manage.py所在目录),避免相对路径解析错位。
  • 如果开发环境需要正常访问媒体文件,记得在项目根urls.py中添加媒体文件的路由适配:
# 项目根urls.py
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # 你原有的其他路由
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

内容的提问来源于stack exchange,提问作者ivbtar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 04:45:40