【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进行访问。

相关推荐
bst@微胖子1 小时前
Python高级语法之selenium
开发语言·python·selenium
wyk123_0461 小时前
Django 连接(sqlserver)数据库方法
数据库·sqlserver·django
查理零世2 小时前
【蓝桥杯集训·每日一题2025】 AcWing 6118. 蛋糕游戏 python
python·算法·蓝桥杯
魔尔助理顾问3 小时前
一个简洁高效的Flask用户管理示例
后端·python·flask
java1234_小锋3 小时前
一周学会Flask3 Python Web开发-request请求对象与url传参
开发语言·python·flask·flask3
诚信爱国敬业友善6 小时前
常见排序方法的总结归类
开发语言·python·算法
李长渊哦6 小时前
使用Druid连接池优化Spring Boot应用中的数据库连接
数据库·spring boot·后端
web135085886356 小时前
【Spring Boot】Spring AOP动态代理,以及静态代理
spring boot·后端·spring
nbsaas-boot7 小时前
Go 自动升级依赖版本
开发语言·后端·golang
架构默片7 小时前
【JAVA工程师从0开始学AI】,第五步:Python类的“七十二变“——当Java的铠甲遇见Python的液态金属
java·开发语言·python