简体   繁体   中英

python cgi http response adds extra byte to content

I have been using a python cgi script to get files from a database everything is working fine but for some reason there seems to be an extra byte added to the file. On the database the size is 10,265 bytes but in the http response the Content-Length is 10,266 the problem seems to be from the http response itself. The problem is the files served are .jar and are being used by a java applcation which then isnt able to load them with the class loader due to this extra byte. The snippet used to serve the download from the server is :

def printFileHeader():
    print 'Content-Type: text/plain;charset=utf-8'
    print

def downloadAddon(addon_id):
    dbConn = sqlite3.connect("addons.db")
    dbCursor = dbConn.cursor()
    dbCursor.execute("SELECT addon_file FROM uploaded WHERE id="+addon_id)
    blobl = dbCursor.fetchone()
    blobl = blobl[0]


    printFileHeader()
    print blobl

the downloadAddon() function is then called with the requested id but no matter where I fetch the file from (blob in database or direct file) the http response always has that extra byte in the content even though server side the file is ok. Any help is welcome.

ps. I know the header is not a proper file header but I put it this way for testing purposes.

I managed to "fix" the issue by providing the content length of the file in the header like so the code now looks like this :

def printFileHeader(size):
    print("Content-Disposition: attachment; filename=addon.jar")
    print("Content-Type: application/octet-stream") 
    print("Content-Length: "+str(size))
    print   

def downloadAddon(addon_id):
    dbCursor.execute("SELECT addon_file FROM uploaded WHERE id="+addon_id)
    blobl = dbCursor.fetchone()
    blobl = blobl[0]
    printFileHeader(len(blobl))
    print(blobl) 

this solves the issue but I still dont understand why so any explanations are still welcome. Also while checking the response before and after the fix here are the last 6 bytes of the file :

Before (with extra byte) : AAAAAK After : AAAAA=

Any explanation as to why is appreciated

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM