4

我有一个werkzeug.datastructures.FileStorage类的对象(称为“img”)(这个对象代表一个文件)。我需要将此文件保存在磁盘上。我可以通过以下方式做到这一点:

img.save(fname)

它工作正常。但在我保存文件之前,我需要检查它的大小。我通过以下方式进行操作:

img.seek(0, os.SEEK_END)
size = img.tell()

它也可以正常工作。但问题是我在检查文件大小后无法保存文件。或者,更准确地说,我在磁盘上得到一个文件,但如果我之前检查过它的大小,它是空的。

如何在不“破坏”文件的情况下检查文件的大小?

4

3 回答 3

6

您忘记在保存文件之前查找文件的开头,因此是空文件

#seek to the end of the file to tell its size
img.seek(0, os.SEEK_END)
size = img.tell()

#seek to its beginning, so you might save it entirely
img.seek(0)    
img.save(fname)
于 2014-09-08T11:06:20.790 回答
1

而不是寻找和告诉替换为:

import os
img.flush()
size = os.fstat(img.fileno()).st_size
于 2014-09-06T06:14:53.067 回答
1

Werkzeug 的 FileStorage 有一个content_length属性:http ://werkzeug.pocoo.org/docs/0.10/datastructures/#werkzeug.datastructures.FileStorage.content_length

img.content_length
于 2015-02-16T19:30:12.323 回答