2014-12-29 49 views
0

我正在運行一個加載登錄頁面的python服務器。所有的html頁面都會加載(它們與託管的html頁面在同一個文件夾中,圖像也一樣),但與html不在同一個文件夾中的圖像不會加載。任何人都知道有什麼問題圖像加載?謝謝。下面的代碼:包含圖像的python服務器

#/usr/bin/python 
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer 
from os import curdir, sep 

PORT_NUMBER = 8080 

#This class will handles any incoming request from 
#the browser 
class myHandler(BaseHTTPRequestHandler): 

    #Handler for the GET requests 
    def do_GET(self): 
     if self.path=="/": 
      self.path="login.html" 

     try: 
      #Check the file extension required and 
      #set the right mime type 

      sendReply = False 
      if self.path.endswith(".html"): 
       mimetype='text/html' 
       sendReply = True 
      if self.path.endswith(".jpg"): 
       mimetype='image/jpg' 
       sendReply = True 
      if self.path.endswith(".gif"): 
       mimetype='image/gif' 
       sendReply = True 
      if self.path.endswith(".js"): 
       mimetype='application/javascript' 
       sendReply = True 
      if self.path.endswith(".css"): 
       mimetype='text/css' 
       sendReply = True 

      if sendReply == True: 
       #Open the static file requested and send it 
       f = open(curdir + sep + self.path) 
       self.send_response(200) 
       self.send_header('Content-type',mimetype) 
       self.end_headers() 
       self.wfile.write(f.read()) 
       f.close() 
      return 


     except IOError: 
      self.send_error(404,'File Not Found: %s' % self.path) 

try: 
    #Create a web server and define the handler to manage the 
    #incoming request 
    server = HTTPServer(('', PORT_NUMBER), myHandler) 
    print 'Started httpserver on port ' , PORT_NUMBER 

    #Wait forever for incoming htto requests 
    server.serve_forever() 

except KeyboardInterrupt: 
    print '^C received, shutting down the web server' 
    server.socket.close() 
+0

也許Web服務器沒有配置爲將該文件擴展名路由到您的Python處理程序? –

+0

哦,像圖像可能是PNG的?是的,讓我檢查一下 – user4402918

+0

我修復了png問題,謝謝。其中一個輸入字段不會加載,但我必須查看該字段。不知道是什麼原因造成的。 – user4402918

回答

1

您可以嘗試爲JPG/PNG文件,下面的代碼相應

if self.path.endswith(".jpg"): 
          f = open(applicationPath + '/' + self.path, 'rb') 
          self.send_response(200) 
          self.send_header('Content-type',  'image/png') 
          self.end_headers() 
          self.wfile.write(f.read()) 
          f.close() 
          return 
1

您必須添加模式= 'RB' 到f =開放(CURDIR +月+自我。路徑),因爲你正在讀取一個二進制文件。