knowing the size of a file using FileField

4 views
Skip to first unread message

Sanjay

unread,
Nov 1, 2006, 7:04:23 AM11/1/06
to TurboGears
Being unable to know how do I get the size of a file being uploaded,
while using FileField. Needing help.

thanks
sanjay

Sanjay

unread,
Nov 7, 2006, 12:12:06 AM11/7/06
to TurboGears

> Being unable to know how do I get the size of a file being uploaded,
> while using FileField. Needing help.

I am a novice in web apps, and need some suggestions on this. Should I
go more specific, presenting the sample code, pl let me know...

thaks a lot
sanjay

Jorge Godoy

unread,
Nov 7, 2006, 4:50:58 AM11/7/06
to turbo...@googlegroups.com
"Sanjay" <skpa...@gmail.com> writes:

Have you inspected what you get with widgets.FileField + either of
validators.FieldStorageUploadConverter or validators.FileUploadKeeper (you can
read the docs for these validators at the formencode package)?

Also take a look at cgi.FieldStorage since it is the base for all this (you
don't need to use it directly, but the docs will point you there).

I believe that *IF* the browser informs the size of the message it will be
inside some dictionary and not available as a property on its own... But I
never used that information for anything...

--
Jorge Godoy <jgo...@gmail.com>

Lee McFadden

unread,
Nov 7, 2006, 7:00:14 AM11/7/06
to turbo...@googlegroups.com

Let's say, for example, your file upload field on your form is called
'upload'. Your controller method should have an `upload` parameter
which is, due to the wonders of CherryPy, a cgi.FieldStorage object.

[code]
filename = upload.filename
mime_type = upload.type
file_handle = upload.file

import os
file_size = os.path.getsize(upload.file.name)
[/code]

This will give you `file_size` which will be the size of the file in
bytes. Divide by the appropriate power of 1024 to get it into Kb, Mb,
etc.

Lee
--
Lee McFadden

blog: http://www.splee.co.uk
work: http://fireflisystems.com

Sanjay

unread,
Nov 8, 2006, 1:56:19 AM11/8/06
to TurboGears
Thanks a lot for the guidences.

While trying "file_size = os.path.getsize(upload.file.name)," I get
Exception: StringIO instance has no attribute 'name'.

Seeing that upload has an attribute "length," I tried that too, but got
-1.

The code below worked, but I don't know whether it is the best way:

data = upload.file.read()
file_size = len(data)

sanjay

Bob Ippolito

unread,
Nov 8, 2006, 2:02:54 AM11/8/06
to turbo...@googlegroups.com
On 11/7/06, Sanjay <skpa...@gmail.com> wrote:
>

This way is probably the best:

upload.file.seek(0, 2)
file_size = upload.file.tell()
upload.file.seek(0)

-bob

Sanjay

unread,
Nov 17, 2006, 6:53:24 AM11/17/06
to TurboGears
Hi Bob, thanks a lot!

sanjay

Reply all
Reply to author
Forward
0 new messages