Python上传文件代码

views视图代码:

import os
from datetime import datetime
from django.shortcuts import render
from day09 import settings

def upload(request):
    return render(request,'app/fileupload.html')

# 文件上传处理
def doupload(request):
    # 获取上传文件
    file = request.FILES.get('picture')
    print(type(file))
    print(file.name,file.size)

    # 文件存储的目标路径
    # path = os.path.join(settings.MDEIA_ROOT,file.name)
    # 日期目录
    myDate = datetime.today().strftime("%Y/%m/%d")

    path = os.path.join(settings.MDEIA_ROOT,myDate)

    # 判定目录是否存在,如果不存在则创建
    if not os.path.exists(path):
        os.makedirs(path) #可以递归创建子目录
    # 文件的绝对路径
    path = os.path.join(path,file.name)

    with open(path,'wb') as fp:
        # 如果文件大于2.5M,分片读写
        if file.multiple_chunks():
            for chip in file.chunks():
                fp.write(chip)
        else:
            fp.write(file.read())
    return HttpResponse("文件上传")

settings中代码:

在设置中上传文件的路径:

#上传文件存放的目录
MDEIA_ROOT = os.path.join(BASE_DIR,'static/upload')

templates模板:

form表单中必须设置enctype="multipart/form-data"属性。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>文件上传</title>
</head>
<body>
<form action="{% url 'app:doupload' %}" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    头像:<input type="file" name="picture"> <input type="submit" value="上传">
</form>
</body>
</html>

如果你想要把存入数据库中的头像取出加载到界面时要注意,数据库中存的是个相对路径,你要进行一下拼接:

datas['icon'] = '/static/uploadfiles/' + user.icon.url
        print(user.icon.url)
        print(user.icon)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值