Python使用AjaxUpload上传图片
我正在尝试用Python来使用AjaxUpload:http://valums.com/ajax-upload/
我想知道如何用Python访问上传的文件。在这个网站上,它说:
* PHP: $_FILES['userfile']
* Rails: params[:userfile]
Python的语法是什么呢?
request.params['userfile'] 似乎不太管用。
提前谢谢你们!这是我现在的代码(使用PIL库,导入为Image)
im = Image.open(request.params['myFile'].file)
3 个回答
1
我正在使用Pyramid框架,之前也遇到过类似的问题。经过一段时间的尝试,我找到了这个解决办法。
from cStringIO import StringIO
from cgi import FieldStorage
fs = FieldStorage(fp=request['wsgi.input'], environ=request)
f = StringIO(fs.value)
im = Image.open(f)
我不确定这是不是“正确”的方法,但看起来是有效的。
1
在编程中,有时候我们需要处理一些数据,这些数据可能来自不同的地方,比如用户输入、文件或者网络请求。为了让程序能够理解这些数据,我们通常需要将它们转换成一种特定的格式。
比如说,如果你从用户那里获取了一些信息,可能是以字符串的形式存在的。字符串就是一串字符,比如“你好”或者“123”。但是有时候,我们需要把这些字符串转换成数字,或者把它们放进一个列表里,这样程序才能更好地处理它们。
在这个过程中,我们可能会用到一些工具或者函数,这些工具可以帮助我们完成转换的工作。就像你在厨房里用刀切菜一样,这些工具可以让我们的工作变得简单和高效。
总之,数据处理就是把不同格式的数据转换成程序能够理解和使用的形式,这样我们的程序才能顺利运行。
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.
0
在Django中,你可以使用:
request.FILES['file']
而不是:
request.POST['file']
我不知道在Pylons中该怎么做……也许概念是一样的……