加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python - Django - 上传文件

发布时间:2020-12-20 12:53:10 所属栏目:Python 来源:网络整理
导读:upload.html: !DOCTYPE htmlhtml lang="en"head meta charset="UTF-8" title上传页面/title/headbodyform action="/upload/" method="post" enctype="multipart/form-data" input type="file" name="upload_file" input type="submit" value="上传"/form/bo

upload.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>上传页面</title>
</head>
<body>

<form action="/upload/" method="post" enctype="multipart/form-data">
    <input type="file" name="upload_file">
    <input type="submit" value="上传">
</form>

</body>
</html>

urls.py:

from django.conf.urls import url
from app01 import views

urlpatterns = [
    url(r‘^upload/‘,views.upload),]

views.py:

from django.shortcuts import render,HttpResponse


# 上传
def upload(request):
    if request.method == "POST":
        # upload_file 为 input 中的 name 属性值
        filename = request.FILES["upload_file"].name  # 获取上传的文件的文件名
        # 在项目目录下创建上传的文件
        with open(filename,"wb") as f:
            # 从上传的文件对象中一点一点读
            for chunk in request.FILES["upload_file"].chunks():
                f.write(chunk)  # 写入本地文件
        return HttpResponse("上传OK")
    else:
        return render(request,"upload.html")

运行结果:

选择一个图片,上传

上传成功

在根目录下可以看到上传的文件

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读