金字塔检测照片上传

Wiz*_*Wiz 1 python pyramid

所以我有一个设置页面,用户可以通过表单上的帖子请求将照片上传到网站,但是现在,我无法检测用户是否上传了照片,因为还有其他部分表单,底部有一个提交按钮.现在,我正在使用if 'file_input' in request.POST:,但它总是返回true,即使用户没有上传照片.如何检测用户是否实际上传了照片.html是:

<form class="group-photo" action="/${groupName}/settings" method="post" style="vertical-align:text-bottom" enctype="multipart/form-data">
            <span style="font-size:17px;font-weight:bold;">Group Photo</span>
            <img style="border-radius:15px;margin-top:5px;margin-bottom:5px;" src="/static/group/${photo_id}_120.${photo_ext}">
            <br>
            <div class="fileinputs">
                <input class="file" type="file" name="file_input" value="Choose image">

                <div class="fakefile" style="margin-left:40px;">
                    <input type="button" class="btn btn-primary" value="Choose image"/>
                </div>
            </div>
            <br/>
            <span style="font-size:17px;font-weight:bold;">Description</span>
            <textarea class="groupbio" name="groupbio">${bio}</textarea>
            <br>
            <br>
            <p><input class="btn btn-success" type="submit" name="submitted" value="Save Changes"></p>
        </form>
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 6

浏览器包括表单中的所有文件输入元素,即使是空的,因此'file_input' in request.POST'测试将始终为True,但如果为空,则为空的unicode字符串(u'').

正确的文件上传有一个文件名,测试:

if 'file_input' in request.POST and hasattr(request.POST['file_input'], 'filename'):
Run Code Online (Sandbox Code Playgroud)

文件上传是cgi.FieldStorage实例,filename测试是cgi模块文档推荐的内容:

如果字段表示上载的文件,则通过value属性或getvalue()方法访问该值会将内存中的整个文件作为字符串读取.这可能不是你想要的.您可以通过测试filename属性或file属性来测试上载的文件.