【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进行区分。

    # file:settings.py
    MEDIA_URL = '/media/'
    MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

    MEDIA_URL 和 MEDIA_ROOT 需要手动绑定。

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

    # 说明:等价于做了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方式

@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

# 字段名: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. 配置上传文件的访问路径和存储路径。

    # settings.py
    # 存储的路由
    MEDIA_URL = '/media/'
    # 存储的位置
    MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

  2. 编写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模型文件。

    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视图文件。

    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路由文件。

    from django.urls import path, re_path
    from . import views
    urlpatterns = [
        path("upload/", views.file_upload, name="file_upload")
    ]

  6. 请求测试。

    文件上传成功。

    使用URL进行访问。

  • 42
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值