How to send image (.jpg, .gif etc) from esp8266 webserver
Posted: Sun May 21, 2017 11:44 am
I am running MicroPython 1.8.7 in ESP12-F. Trying to add images in web pages that are hosted by the "ESP Micropython Server".
I got a little bit success, but still, it's buggy. Whenever the socket connection is closed, image loads no more and inspect elements shows "net::ERR_CONNECTION_RESET" error.
I have stored an image named alogo.gif in the file system of micropython and trying to send it when a client (browser) requests it. If I don't close socket in code, the image loads but loading bar in browser keeps on rotating forever. If stopped by clicking on "cross" (X), image vanishes. Below is my code.:
[CODE]
import machine
html = """<!DOCTYPE html>
<html>
<body>
<h2>Arduino Logo</h2>
<img src="alogo.gif" alt="Arduino">
</body>
</html>
"""
imOpen = open('alogo.gif')
image=imOpen.read()
imOpen.close()
import socket
addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]
s = socket.socket()
s.bind(addr)
s.listen(1)
print('listening on', addr)
while True:
cl, addr = s.accept()
#print('client connected from', addr)
cl_file = cl
while True:
line = cl_file.readline()
line2=str(line)
print(line2)
if not line or line == b'\r\n':
cl.write(html)
#cl.close() commented, so that image can load
break
if line == b'GET /alogo.gif HTTP/1.1\r\n':
cl.write(image)
# cl.close() commented, so that image can load
break
[/CODE]
I've been trying for more than 2 months. This time got a little bit success but need your help to find a proper solution. Thank you all.
I got a little bit success, but still, it's buggy. Whenever the socket connection is closed, image loads no more and inspect elements shows "net::ERR_CONNECTION_RESET" error.
I have stored an image named alogo.gif in the file system of micropython and trying to send it when a client (browser) requests it. If I don't close socket in code, the image loads but loading bar in browser keeps on rotating forever. If stopped by clicking on "cross" (X), image vanishes. Below is my code.:
[CODE]
import machine
html = """<!DOCTYPE html>
<html>
<body>
<h2>Arduino Logo</h2>
<img src="alogo.gif" alt="Arduino">
</body>
</html>
"""
imOpen = open('alogo.gif')
image=imOpen.read()
imOpen.close()
import socket
addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]
s = socket.socket()
s.bind(addr)
s.listen(1)
print('listening on', addr)
while True:
cl, addr = s.accept()
#print('client connected from', addr)
cl_file = cl
while True:
line = cl_file.readline()
line2=str(line)
print(line2)
if not line or line == b'\r\n':
cl.write(html)
#cl.close() commented, so that image can load
break
if line == b'GET /alogo.gif HTTP/1.1\r\n':
cl.write(image)
# cl.close() commented, so that image can load
break
[/CODE]
I've been trying for more than 2 months. This time got a little bit success but need your help to find a proper solution. Thank you all.