在python-ccgi中检测未上载的文件

2024-04-25 16:57:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在提交cgi表单时检测是否上传了可选文件

我读到here我应该做一些类似的事情:

myfile = form["myfile"]
if myfile.file:
    # It's an uploaded file; save it to disk
    file = open('path_to_file','wb')
    file.write(myfile.file.read())
    file.close()

但这对我没用。无论是否上传,文件总是在被写入

对于任何其他字段,我始终可以使用默认值进行检查:

field = cgi.escape(data.getfirst('field','null'))

对于文档中的文件,我看不到解决这个问题的方法。有人帮忙吗

谢谢


Tags: 文件toforman表单fieldifhere
1条回答
网友
1楼 · 发布于 2024-04-25 16:57:49

我用Firefox进行了测试,上传一个带有空文件输入的表单会导致以下帖子内容:

              -135438447855682763402193870
Content-Disposition: form-data; name="foo"; filename=""
Content-Type: application/octet-stream 

              -135438447855682763402193870 

因此,将上载零长度字段。但是,没有设置文件名,因此改为测试filename属性的值

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.

相关问题 更多 >

    热门问题