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

相关推荐
工业甲酰苯胺9 分钟前
Spring Boot 整合 MyBatis 的详细步骤(两种方式)
spring boot·后端·mybatis
Eiceblue26 分钟前
Python 复制Excel 中的行、列、单元格
开发语言·python·excel
NLP工程化41 分钟前
对 Python 中 GIL 的理解
python·gil
新知图书42 分钟前
Rust编程的作用域与所有权
开发语言·后端·rust
极客代码1 小时前
OpenCV Python 深度指南
开发语言·人工智能·python·opencv·计算机视觉
liO_Oil1 小时前
(2024.9.19)在Python的虚拟环境中安装GDAL
开发语言·python·gdal安装
奈斯。zs1 小时前
yjs08——矩阵、数组的运算
人工智能·python·线性代数·矩阵·numpy
Melody20501 小时前
tensorflow-dataset 内网下载 指定目录
人工智能·python·tensorflow
学步_技术1 小时前
Python编码系列—Python抽象工厂模式:构建复杂对象家族的蓝图
开发语言·python·抽象工厂模式
wn5312 小时前
【Go - 类型断言】
服务器·开发语言·后端·golang