Skip to main content
 首页 » 编程设计

python之Pyramid 检测照片上传

2025年05月04日18kuangbin

所以我有一个设置页面,用户可以通过表单的发布请求将照片上传到网站,但是现在,我无法检测用户是否上传了照片,因为还有表单的其他部分,底部有一个提交按钮。现在,我正在使用 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> 

请您参考如下方法:

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

正确的文件上传有一个文件名,对此进行测试:

if 'file_input' in request.POST and hasattr(request.POST['file_input'], 'filename'): 

文件上传是cgi.FieldStorage实例,filename测试是cgi module documentation建议:

If a field represents an uploaded file, accessing the value via the value attribute or the getvalue() method reads the entire file in memory as a string. This may not be what you want. You can test for an uploaded file by testing either the filename attribute or the file attribute.