From 59e22b16b89755cc45d482b23a6308b6b90e72e3 Mon Sep 17 00:00:00 2001 From: Marcin Szewczyk Date: Sat, 24 Oct 2015 18:16:17 +0200 Subject: [PATCH] When possible, guess the content-type of the file being sent Refined PR #285 by rasky to pass all tests --- httpie/input.py | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/httpie/input.py b/httpie/input.py index 07698701..b0fbd772 100644 --- a/httpie/input.py +++ b/httpie/input.py @@ -336,17 +336,14 @@ class Parser(ArgumentParser): 'Invalid file fields (perhaps you meant --form?): %s' % ','.join(file_fields)) - fn, fd = self.args.files[''] + fn, fd, ct = self.args.files[''] self.args.files = {} self._body_from_file(fd) if 'Content-Type' not in self.args.headers: - mime, encoding = mimetypes.guess_type(fn, strict=False) - if mime: - content_type = mime - if encoding: - content_type = '%s; charset=%s' % (mime, encoding) + content_type = get_content_type(fn) + if content_type: self.args.headers['Content-Type'] = content_type def _process_output_options(self): @@ -608,6 +605,16 @@ class DataDict(RequestItemsDict): RequestItems = namedtuple('RequestItems', ['headers', 'data', 'files', 'params']) +def get_content_type(filename): + """Get content type for a filename in format appropriate for Content-Type + headers. + """ + mime, encoding = mimetypes.guess_type(filename, strict=False) + if mime: + content_type = mime + if encoding: + content_type = '%s; charset=%s' % (mime, encoding) + return content_type def parse_items(items, headers_class=CaseInsensitiveDict, @@ -634,7 +641,8 @@ def parse_items(items, try: with open(os.path.expanduser(value), 'rb') as f: value = (os.path.basename(value), - BytesIO(f.read())) + BytesIO(f.read()), + get_content_type(value)) except IOError as e: raise ParseError('"%s": %s' % (item.orig, e)) target = files