4

I'm trying to use AjaxUpload with Python: http://valums.com/ajax-upload/

I would like to know how to access the uploaded file with Python. On the web site, it says:

* PHP: $_FILES['userfile']
* Rails: params[:userfile]

What is the Syntax for Python?

request.params['userfile'] doesn't seem to work.

Thanks in advance! Here is my current code (using PIL imported as Image)

im = Image.open(request.params['myFile'].file)
mjv
  • 73,152
  • 14
  • 113
  • 156
resopollution
  • 19,600
  • 10
  • 40
  • 49

3 Answers3

1
import cgi

#This will give you the data of the file,
# but won't give you the filename, unfortunately.
# For that you have to do some other trick.
file_data = cgi.FieldStorage.getfirst('file')

#<IGNORE if you're not using mod_python>

#(If you're using mod_python you can also get the Request object
# by passing 'req' to the relevant function in 'index.py', like "def func(req):"
# Then you access it with req.form.getfirst('file') instead. NOTE that the
# first method will work even when using mod_python, but the first FieldStorage
# object called is the only one with relevant data, so if you pass 'req' to the
# function you have to use the method that uses 'req'.)

#</IGNORE>

#Then you can write it to a file like so...
file = open('example_filename.wtvr','w')#'w' is for 'write'
file.write(file_data)
file.close()

#Then access it like so...
file = open('example_filename.wtvr','r')#'r' is for 'read'

#And use file.read() or whatever else to do what you want.
sth
  • 222,467
  • 53
  • 283
  • 367
noiztank
  • 11
  • 1
1

I'm working with Pyramid, and I was trying to do the same thing. After some time I came up with this solution.

from cStringIO import StringIO
from cgi import FieldStorage

fs = FieldStorage(fp=request['wsgi.input'], environ=request)
f = StringIO(fs.value)

im = Image.open(f)

I'm not sure if it's the "right" one, but it seems to work.

Dario Zamuner
  • 991
  • 2
  • 14
  • 28
0

in django, you can use:

request.FILES['file']

instead of:

request.POST['file']

i did not know how to do in pylons...maybe it is the same concept..

user149513
  • 1,732
  • 2
  • 11
  • 11