Skip to content

Commit

Permalink
Merge pull request #349 from KeepSafe/file_upload
Browse files Browse the repository at this point in the history
Setup uploaded filename if field value is binary and transfer encoding is not specified
  • Loading branch information
asvetlov committed Apr 29, 2015
2 parents f0b6ffb + 1204db4 commit 475ee7a
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
3 changes: 3 additions & 0 deletions aiohttp/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,9 @@ def add_field(self, name, value, *, content_type=None, filename=None,

if isinstance(value, io.IOBase):
self._is_multipart = True
elif isinstance(value, (bytes, bytearray, memoryview)):
if filename is None and content_transfer_encoding is None:
filename = name

type_options = multidict.MultiDict({'name': name})
if filename is not None and not isinstance(filename, str):
Expand Down
48 changes: 48 additions & 0 deletions tests/test_web_functional.py
Original file line number Diff line number Diff line change
Expand Up @@ -584,3 +584,51 @@ def go():
self.assertEqual('keep-alive', resp.headers['CONNECTION'])

self.loop.run_until_complete(go())

def test_upload_file(self):

here = os.path.dirname(__file__)
fname = os.path.join(here, 'software_development_in_picture.jpg')
with open(fname, 'rb') as f:
data = f.read()

@asyncio.coroutine
def handler(request):
form = yield from request.post()
raw_data = form['file'].file.read()
self.assertEqual(data, raw_data)
return web.Response(body=b'OK')

@asyncio.coroutine
def go():
_, _, url = yield from self.create_server('POST', '/', handler)
resp = yield from request('POST', url,
data={'file': data},
loop=self.loop)
self.assertEqual(200, resp.status)

self.loop.run_until_complete(go())

def test_upload_file_object(self):

here = os.path.dirname(__file__)
fname = os.path.join(here, 'software_development_in_picture.jpg')
with open(fname, 'rb') as f:
data = f.read()

@asyncio.coroutine
def handler(request):
form = yield from request.post()
raw_data = form['file'].file.read()
self.assertEqual(data, raw_data)
return web.Response(body=b'OK')

@asyncio.coroutine
def go():
_, _, url = yield from self.create_server('POST', '/', handler)
resp = yield from request('POST', url,
files={'file': open(fname, 'rb')},
loop=self.loop)
self.assertEqual(200, resp.status)

self.loop.run_until_complete(go())

0 comments on commit 475ee7a

Please sign in to comment.