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

相关推荐
酷爱码44 分钟前
如何通过python连接hive,并对里面的表进行增删改查操作
开发语言·hive·python
画个大饼1 小时前
Go语言实战:快速搭建完整的用户认证系统
开发语言·后端·golang
蹦蹦跳跳真可爱5891 小时前
Python----深度学习(基于深度学习Pytroch簇分类,圆环分类,月牙分类)
人工智能·pytorch·python·深度学习·分类
MinggeQingchun4 小时前
Python - 爬虫-网页解析数据-库lxml(支持XPath)
爬虫·python·xpath·lxml
Python自动化办公社区5 小时前
Python 3.14:探索新版本的魅力与革新
开发语言·python
weixin_贾6 小时前
最新AI-Python机器学习与深度学习技术在植被参数反演中的核心技术应用
python·机器学习·植被参数·遥感反演
张槊哲6 小时前
函数的定义与使用(python)
开发语言·python
船长@Quant6 小时前
文档构建:Sphinx全面使用指南 — 实战篇
python·markdown·sphinx·文档构建
iuyou️6 小时前
Spring Boot知识点详解
java·spring boot·后端
一弓虽6 小时前
SpringBoot 学习
java·spring boot·后端·学习