django文件上传

1.通过在视图函数中加入装饰器去掉csrf安全机制验证:

表示该视图函数不校验csrf安全机制

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def qigeming(request):
    if request.method == "POST":
        file_obj = request.FILES.get("kouge")
        with open(file_obj.name, "wb") as f:
            for line in file_obj.chunks():
                f.write(line)
    return render(request, "qigeming.html")

2.提交文件数据时候注意事项:

①必须在form标签加上:'</span>enctype="multipart/form-data",表示可以传文件'

②默认提交方式为:'enctype="application/x-www-form-urlencoded",表示提交键值对形式数据'

③request.post是集合形式表示,request.body是原型字符串表示

<form action="/qigeming/" method="post" enctype="multipart/form-data">
    <p>写点东西:<input type="file" name="kouge"></p>
    <p><input type="submit" value="提交头皮发麻"></p>
</form>
</body>
</html>

④以流的形式写入图片数据

file_obj = request.FILES.get("kouge")
        with open(file_obj.name, "wb") as f:
            for line in file_obj.chunks():
                f.write(line)
原文地址:https://www.cnblogs.com/zhuxianxiaofan/p/13178017.html