Web2Py - Upload a file and read the content as Zip file

妖精的绣舞 提交于 2019-12-04 21:54:08

web2py form field uploads already are cgi.FieldStorage, you can get the raw uploaded bytes using:

data = request.vars.myfile.value

For a file-like object StringIO is not needed, use:

filelike = request.vars.myfile.file
zip = zipfile.Zipfile(filelike)

HTTP uploads aren't just raw binary, it's mixed-multipart-form encoded. Write request.vars.myfile out to disk and you'll see, it'll say something like

------------------BlahBlahBoundary
Content-Disposition: type="file"; name="myfile"
Content-Type: application/octet-stream

<binary data>
------------------BlahBlahBoundary--

The naive solution for this is, use cgi.FieldStorage(), the example I provide uses wsgi.input, which is part of mod_wsgi.

form = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ)
raw_filw = cStringIO.StringIO(form['myfile'].file.read())

Two things to point out here

  • Always use cStringIO if you have it, it'll be faster than StringIO

  • If you allow uploads like this, you're streaming the file into ram, so, however big the file is is how much ram you'll be using - this does NOT scale. I had to write my own custom MIME stream parser to stream files to disk through python to avoid this. But, if you're learning or this is a proof of concept you should be fine.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!