diff --git a/aiohttp/helpers.py b/aiohttp/helpers.py index 136f49a6db8..5ee3090689c 100644 --- a/aiohttp/helpers.py +++ b/aiohttp/helpers.py @@ -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): diff --git a/tests/test_web_functional.py b/tests/test_web_functional.py index f8c273c680b..61a132da456 100644 --- a/tests/test_web_functional.py +++ b/tests/test_web_functional.py @@ -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())