Django文件上传

模板文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div>
    <form action="/home" method="post" enctype="multipart/form-data">
        {# 添加以下语句 #}
        {% csrf_token %}
        <p>
            <input type="file" name="file">
            <input type="submit" value="提交">
        </p>
    </form>
</div>
</body>
</html>

注意:form 表单里有一句 enctype=”multipart/form-data”,在上传文件的表单里必须要有这个。enctype 属性规定在发送到服务器之前应该如何对表单数据进行编码。

视图函数

def home(request):

    # 判断是否是POST提交
    if request.method == 'POST':
        # 通过文件名字取文件
        file = request.FILES.get('file')
        import os
        # 拼接文件路径,名字
        file_path = os.path.join('upload', file.name)
        # 打开这个文件, 模式为二进制模式读写打开
        f = open(file_path, mode='wb')
        # 写到指定文件中
        for i in file.chunks():
            f.write(i)
        # 关闭文件流
        f.close()
    return render(request, 'home.html')

如果出现Django提交表单报错-CSRF token missing or incorrect.
请看:http://gaocaishun.cn/819.html

更多内容请看个人站点:http://www.gaocaishun.cn

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值