代码之家  ›  专栏  ›  技术社区  ›  resopollution

用AjaxUpload上传python图像

  •  4
  • resopollution  · 技术社区  · 15 年前

    我正在尝试将AjaxUpload与python结合使用: http://valums.com/ajax-upload/

    我想知道如何用python访问上传的文件。网站上写着:

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

    python的语法是什么?

    request.params['userfile']似乎不起作用。

    事先谢谢!这是我的当前代码(使用pil作为图像导入)

    im = Image.open(request.params['myFile'].file)
    
    3 回复  |  直到 14 年前
        1
  •  0
  •   user149513    15 年前

    在Django,您可以使用:

    request.FILES['file']
    

    而不是:

    request.POST['file']
    

    我不知道在塔架上怎么做……也许这是同一个概念……

        2
  •  1
  •   sth Alien    15 年前
    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.
    
        3
  •  1
  •   Dario Zamuner    14 年前

    我在和金字塔合作,我也试着做同样的事情。过了一段时间,我想出了这个解决办法。

    from cStringIO import StringIO
    from cgi import FieldStorage
    
    fs = FieldStorage(fp=request['wsgi.input'], environ=request)
    f = StringIO(fs.value)
    
    im = Image.open(f)
    

    我不确定它是不是“正确”的,但它似乎有效。

    推荐文章