【Django】Django文件上传

文件上传

1 定义&场景

  • 定义:用户可以通过浏览器将图片等文件上传至网站。

  • 场景:

    • 用户上传头像。

    • 上传流程性的文档[pdf,txt等]

2 上传规范-前端[html]

  • 文件上传必须为POST提交方式

  • 表单 <form> 中文件上传时必须带有 enctype="multipart/form-data" 时才会包含文件内容数据。

  • 表单中用 <input type="file" name="xxx"> 标签上传文件。

3 上传规范-后端[Django]

  • 视图函数中,用request.FILES取文件框的内容

  • file=request.FILES['xxx']

说明:

  1. FILE的key对应页面中file框的name值。

  2. file绑定文件流对象。

  3. file.name文件名。

  4. file.file文件的字节流数据。

配置文件的访问路径和存储路径:

  • 在settings.py中设置MEDIA相关配置,Django把用户上传的文件统称为media资源,需要与静态资源static进行区分。

    python 复制代码
    # file:settings.py
    MEDIA_URL = '/media/'
    MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

    MEDIA_URL 和 MEDIA_ROOT 需要手动绑定。

    方法:主路由中添加路由。

    python 复制代码
    # 说明:等价于做了MEDIA_URL开头的路由,Django接到该特征请求后去MEDIA_ROOT路径查找资源
    from django.conf impot settings
    from django.conf.urls.static import static
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

文件写入方案1:传统的open方式

python 复制代码
@csrf_exempt
def file_upload(request):
    if request.method == 'GET':
        return render(request, 'file_upload.html')
    elif request.method == 'POST':
        upload_file = request.FILES['myfile']
        print("上传的文件名是:", upload_file.name)
        file_path = os.path.join(settings.MEDIA_ROOT, upload_file.name)
        with open(file_path, 'wb') as f:
            data = upload_file.file.read()
            f.write(data)
        return HttpResponse("接收文件:" + upload_file.name + "成功")

文件写入方案2:ORM

python 复制代码
# 字段名:FileField(upload='子目录名')
@csrf_exempt
def file_upload(request):
    if request.method == 'GET':
        return render(request, 'file_upload.html')
    elif request.method == 'POST':
        upload_title = request.POST['title']
        upload_file = request.FILES['myfile']
        Content.objects.create(desc=upload_title, myfile=upload_file)
        return HttpResponse("接收文件:" + upload_file.name + "成功")

文件上传代码测试:

  1. 配置上传文件的访问路径和存储路径。

    python 复制代码
    # settings.py
    # 存储的路由
    MEDIA_URL = '/media/'
    # 存储的位置
    MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
  2. 编写html静态文件。

    html 复制代码
    # apps/templates
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>文件上传</title>
    </head>
    <body>
        <form action="/file/upload/" method="post" enctype="multipart/form-data">{% csrf_token %}
            <p>
                <input type="text" name="title">
            </p>
            <p>
                <input type="file" name="myfile">
            </p>
            <p>
                <input type="submit" value="上传">
            </p>
        </form>
    </body>
    </html>
  3. 编写model模型文件。

    python 复制代码
    from django.db import models
    ​
    # Create your models here.
    class Content(models.Model):
        """
        文件存储对象
        """
        title = models.CharField('文件名', max_length=11)
        #子目录的名称即为:upload_to所指定的字段
        picture = models.FileField('子目录名称', upload_to='picture')
  4. 编写view视图文件。

    python 复制代码
    port render
    from django.http import HttpResponse
    from .models import *
    # Create your views here.
    ​
    def file_upload(request):
    ​
        if request.method == 'GET':
            return render(request, 'file_upload.html')
        elif request.method == 'POST':
            title = request.POST['title']
            myfile = request.FILES['myfile']
            Content.objects.create(title=title, picture=myfile)
            return HttpResponse("文件上传成功")
        else:
            return HttpResponse("请求方法错误")
  5. 编写url路由文件。

    python 复制代码
    from django.urls import path, re_path
    from . import views
    urlpatterns = [
        path("upload/", views.file_upload, name="file_upload")
    ]
  6. 请求测试。

    文件上传成功。

    使用URL进行访问。

相关推荐
*愿风载尘*41 分钟前
ksql连接数据库免输入密码交互
数据库·后端
赵英英俊44 分钟前
Python day26
开发语言·python
你怎么知道我是队长44 分钟前
python---eval函数
开发语言·javascript·python
溟洵1 小时前
Qt 窗口 工具栏QToolBar、状态栏StatusBar
开发语言·前端·数据库·c++·后端·qt
ppo921 小时前
MCP简单应用:使用SpringAI + Cline + DeepSeek实现AI创建文件并写入内容
人工智能·后端
创码小奇客1 小时前
Talos 使用全攻略:从基础到高阶,常见问题一网打尽
java·后端·架构
Re2751 小时前
ThreadLocal 入门:搞懂线程私有变量
后端
Rockson1 小时前
期货实时行情接口接入教程
python·api
midsummer_woo2 小时前
基于spring boot的纺织品企业财务管理系统(源码+论文)
java·spring boot·后端
zc-code2 小时前
Spring Boot + @RefreshScope:动态刷新配置的终极指南
java·spring boot·后端