python项目django web html上传文件
一.html文件(文件名为upfile.html)
| 1 2 3 4 5 6 7 8 9 10 11 12 13 | <html> <head>    <meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />   <title>python</title> </head> <body>  <form method="POST" action="/uploadfile/" enctype="multipart/form-data"> <input type="file" name="file" /> <input type="submit" value="提交" /> </form>  <p> {{title}}</p> </body> </html> | 
| 1 2 3 4 | 说明: 1、表单中enctype="multipart/form-data"的意思,是设置表单的MIME编码。默认情况,这个编码格式是application/x-www-form-urlencoded,不能用于文件上传;只有使用了multipart/form-data,才能完整的传递文件数据,进行下面的操作. 2、method="post"文件上传的方式必须为POST方式 3、type="file"类型为文件域 | 
二、、在myApp/url.py中添加配置url
| 1 2 3 4 5 | urlpatterns = [ ..., url('upfile/', views.upfile), url('uploadfile/', views.uploadfile), ] | 
三、在myApp/views.py文件中定义视图
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | def uploadfile(request):    if request.method == 'POST':        f = request.FILES['file']#upfile的html文件中命名的名字        #合成文件在服务器端存储的路径        filePath = os.path.join(settings.MEDIA_ROOT, f.name)        with open(filePath, 'wb') as fp:            for info in f.chunks():#因为文件f的大小并不确定,所以要调用f.chunks()的方法来以文件流的方式一段一段的接收                fp.write(info)        #读取文件内容        with open(filePath, "r") as fff:  # 打开文件            data = fff.read()  # 读取文件        context         = {}        context['title'] = ''        context['image'] = ''        context['show'] = 'none'        context['textarea'] = data        return render(request, 'myform.html', context)    else:        context         = {}        context['title'] = ''        context['image'] = ''        context['show'] = 'none'        context['textarea'] = 'error'        return render(request, 'myform.html', context) def upfile(request):    context         = {}    context['title'] = 'upfile Test '    return render(request, 'formupload.html', context) | 
感谢大佬文章 https://blog.csdn.net/weixin_44387495/article/details/95589379