I know that this question has already been asked before, for instance here: How do I serve image Content-types with Python BaseHTTPServerRequestHandler do_GET method?, but the typical answer of "set your file open mode to binary" is not working for me.
I'm using Windows. All requests for textual data (html, js, css) are satisfied without any problems. Image and font requests are not satisfied properly. The responses being returned always consist of around 150 bytes (but should actually be around 50k). So, essentially empty responses I suppose, with missing images and fonts. I have had no problems up until now under Linux with the same code:
content = open(content_path, 'rb')
...
self.send_response(200)
self.send_header('Content-type', 'image/jpeg')
self.end_headers()
self.wfile.write(content.read)
content.close()
I initially was using the default mode for 'open' and after reading the replies to similar questions, I added the binary flag assuming it would solve the problem, but it didn't. Is there some encoding issue here, maybe? Again, this does work under Linux. Here's the value of 'content' printed to console:
<open file [my_file_path], mode 'rb' at 0x02A9BA18> with mime-type image/jpeg
In case it's relevant, I should probably also mention that the images have all being resized by the python PIL library prior earlier in the application. Any help is appreciated.
You're send string representation of
read
method. Instead call theread
method by appending()
:If the file is huge,
file.read()
make a problem becauseread()
load file content into memory. To prevent that, useshutil.copyfileobj
: