【问题标题】:Pyramid detecting a photo upload金字塔检测照片上传
【发布时间】:2012-09-02 19:49:30
【问题描述】:

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

【问题讨论】:

    标签: python pyramid


    【解决方案1】:

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

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

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

    文件上传是cgi.FieldStorage实例,filename测试是cgi module documentation推荐的:

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

    【讨论】:

      猜你喜欢
      • 2018-12-30
      • 2013-12-03
      • 1970-01-01
      • 1970-01-01
      • 2016-08-25
      • 2019-09-14
      • 2017-06-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多