【django轻量级框架】HTML上传文件拦截到本地

1 注意

这里需要注意两个地方:

表单提交方式需要是 post
form 添加一个属性为 enctype=“multipart/form-data”
form的action,路由,views.py要保持一致

urlpatterns = [
    path('', views.index),
    path('index2', views.index2),
]
from PIL import Image
@csrf_exempt #取消csrf验证
def index(req):

    return render(req, "index.html")


def index2(req):
    print("前端数据: ", req.POST)
    print("file:", req.FILES)

    for item in req.FILES:
        obj = req.FILES.get(item)  # 获取要写入的文件
        filename = obj.name  # 获取文件名
        f = open("C:\\Users\\88304\\Desktop\\Division1\\Retina-Unet-1\\qianduantupian\\01_test.png", 'wb')
        for line in obj.chunks():  # 分块写入
            f.write(line)
        f.close()
    return render(req, 'FG.html')

跳转:

  <form action="/index2" method="POST" enctype="multipart/form-data">
                    {% csrf_token %}

2 在 index.html 加入input 标签

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<h1>hello worlds</h1>
<form action="/klvchen/" method="post" enctype="multipart/form-data">
    <p><input type="file" name="upload"></p>
    <p><input type="submit" value="submit"></p>
</form>

</body>
</html>

3 修改 views.py

from django.shortcuts import render

def klvchen(req):
    print("前端数据: ", req.POST)
    print("file:", req.FILES)

    for item in req.FILES:
        obj = req.FILES.get(item)      # 获取要写入的文件
        filename = obj.name            # 获取文件名
        f = open(filename, 'wb')
        for line in obj.chunks():      # 分块写入
            f.write(line)
        f.close()

    return render(req, "index.html")

成功上传文件
在这里插入图片描述

发布了916 篇原创文章 · 获赞 250 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/weixin_43838785/article/details/105149491