django上传文件

1、另外创建一个app02

 

 

2、在app02/views.py创建 upload视图

 

 

def upload(request):
    if request.method == "POST":
        print( request.FILES.get("myfile"))
        print(type( request.FILES.get("myfile") ))
        file_obj = request.FILES.get("myfile")
        file_name = file_obj.name
        with open( file_name, "wb" ) as f:
            for line in file_obj:
                f.write(line)
    return render(request, 'upload.html')

 

3、在app02/templates里面创建模板 upload.html

 

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1 > 文件上传</h1>
<form action="" method="post" enctype="multipart/form-data">
    <input type="hidden" name="csrfmiddlewaretoken" value="{{ csrf_token}}" >
    <p> <input type="file" name="myfile"> </p>
    <input type="submit">
</form>
</body>
</html>

 

4、配置视图对应的路由

在app02/urls.py里面配置路由

 

 在工程下的urls.py配置路由分发

 

 

5、配置app02/templates对应的settings设置

 

 

6、访问url:  http://127.0.0.1:8080/app02/upload/

 

 提交后,文件会被后台接收:

 

 

 

 

posted on 2019-11-10 13:44  芦苇草鱼  阅读(129)  评论(0编辑  收藏  举报